HTTP POST using JSON in Java

前端 未结 11 996
南笙
南笙 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 07:58

    You can make use of Gson library to convert your java classes to JSON objects.

    Create a pojo class for variables you want to send as per above Example

    {"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

    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

    import com.google.gson.Gson;
    
    0 讨论(0)
  • 2020-11-22 08:00

    It's probably easiest to use HttpURLConnection.

    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; you need to serialize it and then pass it to an HttpURLConnection to POST.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 08:06

    Java 8 with apache httpClient 4

    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();
            }
    
    0 讨论(0)
  • 2020-11-22 08:08

    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();
    }
    
    0 讨论(0)
  • 2020-11-22 08:08

    You can use the following code with 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

    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));
    
    0 讨论(0)
提交回复
热议问题