【问题标题】:HTTP POST using JSON in Java在 Java 中使用 JSON 的 HTTP POST
【发布时间】: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


    【解决方案1】:

    使用HttpURLConnection 可能是最简单的。

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

    您将使用 JSONObject 或其他任何东西来构建您的 JSON,但不会处理网络;您需要对其进行序列化,然后将其传递给 HttpURLConnection 以进行 POST。

    【讨论】:

    • JSONObject j = new JSONObject(); j.put("名字", "我的名字"); j.put("年龄", "20");像那样?如何序列化?
    • @asdf007 只需使用j.toString()
    • 没错,这个连接被阻塞了。如果您要发送 POST,这可能没什么大不了的;如果您运行网络服务器,这一点更为重要。
    • HttpURLConnection 链接已失效。
    • 你能发布如何将 json 发布到正文的示例吗?
    【解决方案2】:

    这是你需要做的:

    1. 获取 Apache HttpClient,这将使您能够发出所需的请求
    2. 用它创建一个HttpPost请求并添加标题application/x-www-form-urlencoded
    3. 创建一个StringEntity,您将把 JSON 传递给它
    4. 执行调用

    代码大致如下(您仍然需要对其进行调试并使其工作):

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

    【讨论】:

    • 您可以,但最好将其抽象为 JSONObject,就像您直接在字符串中一样,您可能会错误地对字符串进行编程并导致语法错误。通过使用 JSONObject,您可以确保您的序列化始终遵循正确的 JSON 结构
    • 原则上,它们都只是传输数据。唯一的区别是您如何在服务器中处理它。如果您只有很少的键值对,那么带有 key1=value1、key2=value2 等的普通 POST 参数可能就足够了,但是一旦您的数据更复杂,尤其是包含复杂的结构(嵌套对象、数组),您会想要开始考虑使用 JSON。使用键值对发送复杂的结构将非常讨厌并且难以在服务器上解析(您可以尝试一下,您会立即看到它)。还记得我们不得不这样做的那一天 urgh.. 它并不漂亮..
    • 很高兴为您提供帮助!如果这是您正在寻找的内容,您应该接受答案,以便其他有类似问题的人能够很好地引导他们提出问题。您可以使用答案上的复选标记。如果您还有其他问题,请告诉我
    • 内容类型不应该是“应用程序/json”。 'application/x-www-form-urlencoded' 意味着字符串的格式类似于查询字符串。 NM 我明白你做了什么,你把 json blob 作为一个属性的值。
    • 应使用 CloseableHttpClient 替换已弃用的部分,它为您提供 .close() - 方法。见stackoverflow.com/a/20713689/1484047
    【解决方案3】:

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

    【讨论】:

    • 我们必须明确添加内容类型吗?下面的工作吗? entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));问,因为它不适合我。使用 httpclient-4.5.1.jar。
    • @DarshanGopalR 你的似乎是一种不同的使用方式。我在 8 年前写了这个答案,并没有测试 httpclient 的较新版本。我会尝试尽可能地坚持这个例子。我可以在一个新项目中尝试一下,如有必要,我会更新答案。
    【解决方案4】:

    您可以利用 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 httpClient = new DefaultHttpClient();' 创建一个实例
    • 现在不推荐使用,我们必须使用 HttpClient httpClient = HttpClientBuilder.create().build();
    • 如何导入HttpClientBuilder?
    • 我发现在 StringUtils 构造函数中使用 ContentType 参数并传入 ContentType.APPLICATION_JSON 而不是手动设置标头会稍微干净一些。
    【解决方案5】:

    试试这个代码:

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

    【讨论】:

    • 谢谢!只有你的回答解决了编码问题:)
    • @SonuDhakar 为什么你将application/json 发送为接受标头和内容类型
    • DefaultHttpClient 似乎已被弃用。
    【解决方案6】:

    我发现这个问题正在寻找有关如何将发布请求从 Java 客户端发送到 Google Endpoints 的解决方案。以上答案,很可能是正确的,但不适用于 Google Endpoints。

    Google 端点解决方案。

    1. 请求正文必须只包含 JSON 字符串,而不是名称=值对。
    2. 内容类型标头必须设置为“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 来完成。

    【讨论】:

      【解决方案7】:
      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();
      }
      

      【讨论】:

      • 请考虑编辑您的帖子,以添加更多关于您的代码的作用以及它为何能解决问题的说明。大部分只包含代码的答案(即使它正在工作)通常不会帮助 OP 理解他们的问题
      【解决方案8】:

      我推荐 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);
      

      我强烈建议在使用前阅读文档。

      【讨论】:

      • 你为什么在上面的回答中提出这个建议?
      • 因为它使用起来非常简单,并且可以通过响应进行操作。
      【解决方案9】:

      您可以在 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));
      

      【讨论】:

      • 关键是添加 ContentType.APPLICATION_JSON 否则它对我不起作用 new StringEntity(payload, ContentType.APPLICATION_JSON)
      【解决方案10】:

      对于 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();
      

      您可以使用来自InputStreamStringFile 的发布者。可以使用 Jackson 将 JSON 转换为 StringIS

      【讨论】:

        【解决方案11】:

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

        【讨论】:

          【解决方案12】:

          实现 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());
          

          【讨论】:

            猜你喜欢
            • 2015-07-11
            • 1970-01-01
            • 2016-03-06
            • 1970-01-01
            • 1970-01-01
            • 2017-05-23
            • 1970-01-01
            相关资源
            最近更新 更多