Android HTTPUrlConnection:如何在http正文中设置发布数据? [英] Android HTTPUrlConnection : how to set post data in http body?
本文介绍了Android HTTPUrlConnection:如何在http正文中设置发布数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了我的HTTPUrlConnection:
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);
我不知道如何在http正文中设置postData.怎么做?我最好改用HttpPost
吗?
I don't know how to set postData in http body. How to do so? Would I better use HttpPost
instead?
感谢您的帮助.
推荐答案
如果只想发送String,请尝试以下方式:
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();
但是,如果您想以Json的身份发送,请将内容类型"更改为:
But if you want to send as Json change Content type to:
conn.setRequestProperty("Content-Type","application/json");
现在我们的str
我们可以写:
and now our str
we can write:
String str = "{\"x\": \"val1\",\"y\":\"val2\"}";
希望这会有所帮助,
这篇关于Android HTTPUrlConnection:如何在http正文中设置发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文