我成功地使用此代码HTTP通过GET方法发送 带有一些参数的请求
void sendRequest(String request)
{
// i.e.: request = "http://example.com/index.php?param1=a¶m2=b¶m3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
}
Run Code Online (Sandbox Code Playgroud)
现在我可能需要通过POST方法发送参数(即param1,param2,param3),因为它们非常长.我想在该方法中添加一个额外的参数(即String httpMethod).
如何能够尽可能少地更改上面的代码,以便能够通过GET或发送参数POST?
我希望改变
connection.setRequestMethod("GET");
Run Code Online (Sandbox Code Playgroud)
至
connection.setRequestMethod("POST");
Run Code Online (Sandbox Code Playgroud)
本来可以做到的,但参数仍然是通过GET方法发送的.
有HttpURLConnection任何方法可以帮助吗?有没有有用的Java构造?
任何帮助将非常感谢.
我继承了代码
import org.apache.http.client.HttpClient;
...
HttpClient httpclient = createHttpClientOrProxy();
try {
HttpPost postRequest = postRequest(data, url);
body = readResponseIntoBody(body, httpclient, postRequest);
} catch( IOException ioe ) {
throw new RuntimeException("Cannot post/read", ioe);
} finally {
httpclient.getConnectionManager().shutdown(); // ** Deprecated
}
private HttpClient createHttpClientOrProxy() {
HttpClient httpclient = new DefaultHttpClient();
/*
* Set an HTTP proxy if it is specified in system properties.
*
* http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
* http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientExecuteProxy.java
*/
if( isSet(System.getProperty("http.proxyHost")) ) {
log.warn("http.proxyHost = " + System.getProperty("http.proxyHost") );
log.warn("http.proxyPort = " …Run Code Online (Sandbox Code Playgroud) 我正在尝试将JSON对象发送到自定义端口上的服务器。但是,我从未从服务器返回任何响应。我认为错误可能出在字符串实体中,但我无法弄清楚它是什么。
我看过这些其他问题:
如何使用Java使用正确的实体而不使用任何库来构建http发布请求?
他们都没有解决我的问题。我正在尝试使用“在Java中使用JSON的HTTP POST”解决方案(16票),但是它不起作用。
这是我的代码:
public void reset() {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
System.out.println("Start");
jsonURL = "http://x.x.x.x:3994";
HttpPost request = new HttpPost(jsonURL);
StringEntity params = new StringEntity("{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}");
request.addHeader("Content-Type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println("End");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
Run Code Online (Sandbox Code Playgroud)
控制台在开始时会显示“开始”,但是我从“结束”中没有任何输出,也从异常中没有任何堆栈跟踪。调试时,调试器将在“ httpClient.execute(request)”行停止,并且永远不会继续。
当我从终端运行此命令时:
echo '{"id":1, "method":"object.deleteAll", "params":["subscriber"]} ' | nc x.x.x.x 3994
Run Code Online (Sandbox Code Playgroud)
一切正常执行,服务器收到我的请求。
我认为我的问题可能出在,StringEntity但我不确定。
编辑:
使用Wireshark,我能够捕获此发送到服务器的数据包:
POST / HTTP/1.1 Content-Type: application/json Content-Length: …Run Code Online (Sandbox Code Playgroud) 我正试图从远程服务器获得响应.这是我的代码:
private static String baseRequestUrl = "http://www.pappico.ru/promo.php?action=";
@SuppressWarnings("deprecation")
public String executeRequest(String url) {
String res = "";
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response;
try {
//url = URLEncoder.encode(url, "UTF-8");
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
Log.d("MAPOFRUSSIA", response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inStream = entity.getContent();
res = streamToString(inStream);
inStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
public String registerUser(int userId, String userName) {
String res = "";
String …Run Code Online (Sandbox Code Playgroud) 我正在做一个Android程序,它应该将数据从平板电脑发送到PHP Web服务.发送JSON的代码:
package com.example.shvalidation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainMenuScreen extends Activity {
//JSON Variables
JSONParser jsonParser = new JSONParser();
String pid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu_layout);
new TestThread().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; …Run Code Online (Sandbox Code Playgroud) 我需要访问github graphql API以获取有关某个存储库的一些数据。以下curl命令工作正常
curl -i -H "Authorization: bearer myGithubToken" -X POST -d '{"query": "query { repository(owner: \"wso2-extensions\", name: \"identity-inbound-auth-oauth\") { object(expression:\"83253ce50f189db30c54f13afa5d99021e2d7ece\") { ... on Commit { blame(path: \"components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java\") { ranges { startingLine endingLine age commit { message url history(first: 2) { edges { node { message url } } } author { name email } } } } } } } }"}' https://api.github.com/graphql
Run Code Online (Sandbox Code Playgroud)
现在我需要调用与Java操作输出相同的方法。这是我尝试过的代码,
public void callGraphqlApi(){
CloseableHttpClient httpClientForGraphql = null;
CloseableHttpResponse httpResponseFromGraphql= null; …Run Code Online (Sandbox Code Playgroud)