user_1357
user_1357

Reputation: 7940

How to write JSON into API call using Java HttpURLConnection?

I need to make a cross domain API call fron one server to another one. Basically I need to make a POST request to send Json over the wire. I am using Jackson to handle the Json parsing on both applications. Below is the code I use to execute the request from one domain.

URL url = new URL(url); //This is url to POST method of the Servlet on another domain
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
jsonParser.writeValue(connection.getOutputStream(),dto);

When I run above code to make a request, doPost() on the other server is executed correctly (so API call is going through) however there is nothing in the InputStream, for example readLine() call below return null.

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream( )));
reader.readLine() 

How can I correctly send the Json using HttpUrLConnection (Am I missing configuration information)? Also how do I read this Json from the Servlet as a receiver of this API call?(note as explained above this API call is invoking the Servlet on the other domain)

note: I did check the Using java.net.URLConnection to fire and handle HTTP requests, but no help

Thanks!

Upvotes: 1

Views: 4850

Answers (1)

Tomas Narros
Tomas Narros

Reputation: 13488

I have checked the API DOC for Jackson ObjectMapper class, for the method writeValue (here) There, it states that the method won't close the stream explicitly, unless you have set it at the JSonFactory, or when you close the Mapper.

Then, maybe you'll need to add an explicit flush() and a close() on the OutputStream:

OutputStream out=connection.getOutputStream();
try {
    jsonParser.writeValue(out,dto);
    out.flush();
//catch and handle the exceptions if needed
} finally {
    out.close();
}

Upvotes: 1

Related Questions