HTTP POST using JSON in Java

前端 未结 11 1109
南笙
南笙 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: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();
            }
    

提交回复
热议问题