I've already created my HTTPUrlConnection :
String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
// How to add postData as http body?
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
I don't know how to set postData in http body. How to do so? Would I better use HttpPost
instead?
Thanks for your help.
If you want to send String only try this way:
But if you want to send as Json change Content type to:
and now our
str
we can write:Hope it will help,
Guruparan's link in the comment above gives a really nice answer to this question. I highly recommend looking at it. Here is the principle that makes his solution work:
From what I understand, the HttpURLConnection represents the response body as an OutputStream. So you need to call something like:
get the connection's output stream
write the response body
close the output stream
and then carry on your merry way with the connection (which you will still need to close).