我想在Java中使用JSON进行简单的HTTP POST。在Java中使用JSON的HTTP POST
假设URL是www.site.com
,它需要在标注为'details'
例如价值{"name":"myname","age":"20"}
。
我该如何去创建POST的语法?
我也无法在JSON Javadoc中找到POST方法。
我想在Java中使用JSON进行简单的HTTP POST。在Java中使用JSON的HTTP POST
假设URL是www.site.com
,它需要在标注为'details'
例如价值{"name":"myname","age":"20"}
。
我该如何去创建POST的语法?
我也无法在JSON Javadoc中找到POST方法。
这可能是最容易使用的HttpURLConnection。
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
您将使用的JSONObject或什么来构建你的JSON,但不处理网络;你需要序列化它,然后将它传递给HttpURLConnection以POST。
以下是你需要做的:
钍E码大致样子(你仍需要调试它,让它工作)
//Deprecated
//HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//handle response here...
}catch (Exception ex) {
//handle exception here
} finally {
//Deprecated
//httpClient.getConnectionManager().shutdown();
}
@ MOMO的回答为Apache HttpClient的,版本4.3.1或更高版本。我使用JSON-Java
建立我的JSON对象:
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
谢谢,但不是“application/x-www-form-urlencoded”,内容类型应该是“应用程序/ json”! –
您可以使用GSON库到您的Java类转换成JSON对象。
创建要发送 按照以上示例
{"name":"myname","age":"20"}
成为
class pojo1
{
String name;
String age;
//generate setter and getters
}
一旦你设置pojo1类中的变量,你可以给变量一个POJO类,使用下面的代码
String postUrl = "www.site.com";// put in your url
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
这些都是进口
import org.apache.http.HttpEntity;
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.HttpClientBuilder;
和GSON
import com.google.gson.Gson;
嗨,你如何创建你的httpClient对象?这是一个接口 – user3290180
是的,这是一个接口。您可以使用'HttpClient httpClient = new DefaultHttpClient()'创建一个实例;'' – Prakash
现在已经弃用了,我们必须使用HttpClient httpClient = HttpClientBuilder.create()。build(); – user3290180
试试这个代码:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
我发现这个问题,寻找有关如何从Java客户端发送POST请求,谷歌端点解决方案。以上答案很可能是正确的,但在Google Endpoint的情况下不起作用。
Google终端解决方案。
内容类型标头必须设置为“application/json”。
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
"{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
public static void post(String url, String param) throws Exception{
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(param.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
它肯定可以使用HttpClient来完成。
protected void sendJson(final String play, final String prop) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the childThread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://192.168.0.44:80");
json.put("play", play);
json.put("Properties", prop);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch (Exception e) {
e.printStackTrace();
showMessage("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
我建议http-request它基于Apache HTTP API。
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);
int statusCode = responseHandler.getStatusCode();
String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null.
}
如果你想发送JSON
作为请求体,您可以:
ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);
我使用前higly建议更换阅读文档。
JSONObject j = new JSONObject(); j.put(“name”,“myname”); j.put(“age”,“20”); 那样?我如何序列化它? – asdf007
@ asdf007只需使用'j.toString()'。 –
但这个连接不是异步....仪式? – gumuruh