我想在Java中使用JSON进行简单的HTTP POST。
假设URL是www.site.com
并且它接收标记为'details'
的值为{"name":"myname","age":"20"}
,例如。
我该如何创建POST语法?
我在JSON Javadocs中也找不到POST方法。
以下是需要执行的步骤:
HttpClient
,这将使您能够进行所需的请求HttpPost
请求并添加头信息 application/x-www-form-urlencoded
StringEntity
,您将向其中传递JSON数据代码大致如下(您仍需要调试并使其正常工作):
// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
// @Deprecated httpClient.getConnectionManager().shutdown();
}
{"name":"myname","age":"20"}
变成class pojo1
{
String name;
String age;
//generate setter and getters
}
在设置了POJO1类中的变量后,您可以使用以下代码发送该类:
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;
@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();
}
httpclient
。我建议尽可能遵循示例。如果需要,在新项目中可以试一下,我会更新答案。 - Leonel Sanches da Silva使用HttpURLConnection可能是最容易的。
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
您将使用JSONObject或其他工具构建您的JSON,但不要用它来处理网络;您需要将其序列化,然后将其传递给HttpURLConnection进行POST操作。
j.toString()
。 - Alex Churchillprotected 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();
}
试试这段代码:
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();
}
application/json
作为 accept header,又将它作为 content-type 发送? - Kasun SiyambalapitiyaDefaultHttpClient
已经被弃用。 - sdgfsdh我发现这个问题是在寻找如何从Java客户端向Google终端发送POST请求的解决方案。上面的答案很可能是正确的,但在Google终端的情况下不起作用。
Google终端的解决方案。
内容类型标头必须设置为"application/json"。
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
"{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
public static void post(String url, String json ) 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(json.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
当然也可以使用HttpClient来完成。
对于Java 11,您可以使用新的HTTP客户端:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost/api"))
.header("Content-Type", "application/json")
.POST(ofInputStream(() -> getClass().getResourceAsStream(
"/some-data.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
您可以使用来自 InputStream
、String
和 File
的出版商。使用Jackson可以将JSON转换为String
或IS
。
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
response = client.execute(request);
此外,您可以创建一个JSON对象,并将字段放入该对象中,如下所示
HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
Java 11标准化了HTTP客户端API,实现了HTTP/2和Web Socket,并且可以在java.net.HTTP.*找到:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("www.site.com"))
.header("content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());