-5

I want write simple code in JAVA that will allow to me send HTTP POST request to server

1)The request will contain the next JSON

{ "Key": "asd", "dId": 123456, "SomeData": { "id": 12345, "name": "abcd" }, "Url": "https://google.com/", "tdId": 1, "wdId": 0 }

2)display the JSON answer from the server

have seen lots of tutorial videos on YouTube but no one explain it in simple way step by step

Ru8ik
  • 305
  • 4
  • 5
  • https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java – PimJ May 16 '19 at 09:41
  • Apache has a [Fluent API](https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html) for HTTP requests, with examples – Arthur Attout May 16 '19 at 09:42

2 Answers2

0

If you don't want to fight with the JRE internal HttpURLConnection then you should have a look at the HttpClient from Apache Commons:

org.apache.commons.httpclient

final HttpClient httpClient = new HttpClient();

String url; // your URL
String body; // your JSON
final int contentLength = body.length();

PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Accept", "application/json");
postMethod.setRequestHeader("Content-Type", "application/json; charset=utf-8");
postMethod.setRequestHeader("Content-Length", String.valueOf(contentLength));
postMethod.setRequestEntity(new StringRequestEntity(body, "application/json", "utf-8"));

final int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != 200) 
    throw new java.io.IOException(statusCode + ": " + HttpStatus.getStatusText(statusCode));

java.io.InputStream responseBodyAsStream = postMethod.getResponseBodyAsStream();
java.io.StringWriter writer=new StringWriter();
org.apache.commons.io.IOUtils.copy(responseBodyAsStream,writer,java.nio.charset.StandardCharsets.UTF_8);

String responseJSON=writer.toString();

Sascha
  • 1,320
  • 10
  • 16
0

Since JDK 9, there is HttpClient class. In JDK 9 and JDK 10, it was in incubator status. Since JDK 11 it is no longer incubator. I did not see any mention in your post as to which JDK version you are using. Did I miss something? Here is link to javadoc for JDK 11...

java.net.http.HttpClient

In my opinion, the advantage of using JDK's HttpClient class means no third-party dependency.

Abra
  • 19,142
  • 7
  • 29
  • 41