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

该博客探讨了如何使用Java的HttpURLConnection类进行POST请求,包括设置请求方法、内容类型和正文。给出了将字符串数据作为HTTP请求体的方法,并对比了HttpPost的选择。提供了将字符串和JSON数据写入输出流的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

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.

回答1:

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,

回答2:

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).

来源:https://stackoverflow.com/questions/20020902/android-httpurlconnection-how-to-set-post-data-in-http-body

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值