Android HTTPUrlConnection : how to set post data in http body?

Rob picture Rob · Nov 16, 2013 · Viewed 63.5k times · Source

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.

Answer

Maxim Shoustin picture Maxim Shoustin · Nov 16, 2013

If you want to send String only try this way:

String str =  "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );    
os.close();

But if you want to send as Json change Content type to:

conn.setRequestProperty("Content-Type","application/json");  

and now our str we can write:

String str =  "{\"x\": \"val1\",\"y\":\"val2\"}";

Hope it will help,