Question
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":"myname","age":"20"} labeled as 'details' for example. How would I go about creating the syntax for the POST? I also can't seem to find a POST method in the JSON Javadocs.
How-To
Here is what you need to do:
The code roughly looks like (you will still need to debug it and make it work):
- HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
- try {
- HttpPost request = new HttpPost("http://yoururl");
- StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
- request.addHeader("content-type", "application/x-www-form-urlencoded");
- request.setEntity(params);
- HttpResponse response = httpClient.execute(request);
- //handle response here...
- }catch (Exception ex) {
- //handle exception here
- } finally {
- //Deprecated
- //httpClient.getConnectionManager().shutdown();
- }
* How to convert hashmap to JSON object in Java
沒有留言:
張貼留言