HTTP POST using JSON in Java

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

提交回复
热议问题