我想在Java中使用JSON制作一个简单的HTTP POST。
假设URL是www.site.com
它接收值{"name":"myname","age":"20"},例如标记为" details "。
我将如何着手创建POST的语法?
我似乎也找不到JSON Javadocs中的POST方法。
我想在Java中使用JSON制作一个简单的HTTP POST。
假设URL是www.site.com
它接收值{"name":"myname","age":"20"},例如标记为" details "。
我将如何着手创建POST的语法?
我似乎也找不到JSON Javadocs中的POST方法。
当前回答
以下是你需要做的:
获取Apache HttpClient,这将使您能够发出所需的请求 用它创建一个HttpPost请求,并添加头应用程序/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();
}
其他回答
我推荐在apache http api上构建http-request。
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);
我强烈建议在使用前阅读文档。
我发现这个问题寻找如何从java客户端发送post请求到谷歌端点的解决方案。以上答案,很可能是正确的,但在谷歌端点的情况下不工作。
谷歌端点的解决方案。
Request body must contains only JSON string, not name=value pair. Content type header must be set to "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(); } It sure can be done using HttpClient as well.
对于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中的发布者。将JSON转换为字符串或IS可以用Jackson完成。
@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();
}
以下是你需要做的:
获取Apache HttpClient,这将使您能够发出所需的请求 用它创建一个HttpPost请求,并添加头应用程序/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();
}