【发布时间】:2021-01-02 01:33:05
【问题描述】:
我想在 Java 中使用 JSON 制作一个简单的 HTTP POST。
假设网址是www.site.com
它接受值{"name":"myname","age":"20"},例如标记为'details'。
我将如何为 POST 创建语法?
我似乎也无法在 JSON Javadocs 中找到 POST 方法。
【问题讨论】:
我想在 Java 中使用 JSON 制作一个简单的 HTTP POST。
假设网址是www.site.com
它接受值{"name":"myname","age":"20"},例如标记为'details'。
我将如何为 POST 创建语法?
我似乎也无法在 JSON Javadocs 中找到 POST 方法。
【问题讨论】:
使用HttpURLConnection 可能是最简单的。
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
您将使用 JSONObject 或其他任何东西来构建您的 JSON,但不会处理网络;您需要对其进行序列化,然后将其传递给 HttpURLConnection 以进行 POST。
【讨论】:
j.toString()。
这是你需要做的:
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();
}
【讨论】:
@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 的较新版本。我会尝试尽可能地坚持这个例子。我可以在一个新项目中尝试一下,如有必要,我会更新答案。
您可以利用 Gson 库将您的 java 类转换为 JSON 对象。
为要发送的变量创建一个 pojo 类 按照上面的例子
{"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;
【讨论】:
试试这个代码:
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 发送为接受标头和内容类型
DefaultHttpClient 似乎已被弃用。
我发现这个问题正在寻找有关如何将发布请求从 Java 客户端发送到 Google Endpoints 的解决方案。以上答案,很可能是正确的,但不适用于 Google Endpoints。
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 来完成。
【讨论】:
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);
我强烈建议在使用前阅读文档。
【讨论】:
您可以在 Apache HTTP 中使用以下代码:
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 client:
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。
【讨论】:
带有 apache httpClient 4 的 Java 8
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");
String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";
try {
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// set your POST request headers to accept json contents
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
// your closeablehttp response
CloseableHttpResponse response = client.execute(httpPost);
// print your status code from the response
System.out.println(response.getStatusLine().getStatusCode());
// take the response body as a json formatted string
String responseJSON = EntityUtils.toString(response.getEntity());
// convert/parse the json formatted string to a json object
JSONObject jobj = new JSONObject(responseJSON);
//print your response body that formatted into json
System.out.println(jobj);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
【讨论】:
实现 HTTP/2 和 Web Socket 的 HTTP 客户端 API 的 Java 11 标准化,可在 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());
【讨论】: