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

﹥>﹥吖頭↗ 提交于 2019-11-28 20:02:32

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,

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

OutputStream op = conn.getOuputStream();

write the response body

op.write( [/*your string in bit form*/] );

close the output stream

op.close();

and then carry on your merry way with the connection (which you will still need to close).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!