HTTP POST using JSON in Java

前端 未结 11 1002
南笙
南笙 2020-11-22 07:24

I would like to make a simple HTTP POST using JSON in Java.

Let\'s say the URL is www.site.com

and it takes in the value {\"name\":\"mynam

11条回答
  •  忘了有多久
    2020-11-22 08:00

    I found this question looking for solution about how to send post request from java client to Google Endpoints. Above answers, very likely correct, but not work in case of Google Endpoints.

    Solution for Google Endpoints.

    1. Request body must contains only JSON string, not name=value pair.
    2. 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.

提交回复
热议问题