简体   繁体   English

HTTP POST 使用 Java 中的 JSON

[英]HTTP POST using JSON in Java

I would like to make a simple HTTP POST using JSON in Java.我想在 Java 中使用 JSON 制作一个简单的 HTTP POST。

Let's say the URL is www.site.com假设 URL 是www.site.com

and it takes in the value {"name":"myname","age":"20"} labeled as 'details' for example.例如,它接受标记为'details'的值{"name":"myname","age":"20"}

How would I go about creating the syntax for the POST?我将如何为 POST 创建语法?

I also can't seem to find a POST method in the JSON Javadocs.我似乎也无法在 JSON Javadocs 中找到 POST 方法。

Here is what you need to do:以下是您需要做的:

  1. Get the Apache HttpClient , this would enable you to make the required request获取 Apache HttpClient ,这将使您能够发出所需的请求
  2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded用它创建一个HttpPost请求并添加头application/x-www-form-urlencoded
  3. Create a StringEntity that you will pass JSON to it创建一个StringEntity ,您会将 JSON 传递给它
  4. Execute the call执行调用

The code roughly looks like (you will still need to debug it and make it work):代码大致如下(您仍然需要调试它并使其工作):

// @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(); 
}

You can make use of Gson library to convert your java classes to JSON objects.您可以使用 Gson 库将您的 Java 类转换为 JSON 对象。

Create a pojo class for variables you want to send as per above Example按照上面的示例为要发送的变量创建一个 pojo 类

{"name":"myname","age":"20"}

becomes变成

class pojo1
{
   String name;
   String age;
   //generate setter and getters
}

once you set the variables in pojo1 class you can send that using the following code在 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);

and these are the imports这些是进口

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;

and for GSON和 GSON

import com.google.gson.Gson;

@momo's answer for Apache HttpClient, version 4.3.1 or later. @momo 对 Apache HttpClient 版本 4.3.1 或更高版本的回答。 I'm using JSON-Java to build my JSON object:我正在使用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();
}

It's probably easiest to use HttpURLConnection .使用HttpURLConnection可能是最简单的。

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139 http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

You'll use JSONObject or whatever to construct your JSON, but not to handle the network;您将使用 JSONObject 或其他任何东西来构建您的 JSON,但不会处理网络; you need to serialize it and then pass it to an HttpURLConnection to POST.您需要对其进行序列化,然后将其传递给 HttpURLConnection 以进行 POST。

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();
}

Try this code:试试这个代码:

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();
}

I found this question looking for solution about how to send post request from java client to Google Endpoints.我发现这个问题正在寻找有关如何将发布请求从 java 客户端发送到 Google Endpoints 的解决方案。 Above answers, very likely correct, but not work in case of Google Endpoints.以上答案,很可能是正确的,但不适用于 Google Endpoints。

Solution for Google Endpoints. Google Endpoints 的解决方案。

  1. Request body must contains only JSON string, not name=value pair.请求正文必须仅包含 JSON 字符串,而不是名称=值对。
  2. Content type header must be set to "application/json".内容类型标头必须设置为“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.当然也可以使用 HttpClient 来完成。

You can use the following code with Apache HTTP:您可以在 Apache HTTP 中使用以下代码:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

response = client.execute(request);

Additionally you can create a json object and put in fields into the object like this此外,您可以创建一个 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));

For Java 11 you can use the new HTTP client :对于 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();

You can use publishers from InputStream , String , File .您可以使用InputStreamStringFile Converting JSON to a String or IS can be done with Jackson.可以使用 Jackson 将 JSON 转换为StringIS

Java 8 with apache httpClient 4带有 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();
        }

I recomend http-request built on apache http api.我推荐建立在 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. 
}

If you want send JSON as request body you can:如果您想将JSON作为请求正文发送,您可以:

  ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);

I higly recomend read documentation before use.我强烈建议在使用前阅读文档。

Java 11 standardization of HTTP client API that implements HTTP/2 and Web Socket, and can be found at java.net.HTTP.*:实现 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM