Android HTTPUrlConnection:如何在http正文中设置发布数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20020902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:10:46  来源:igfitidea点击:

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

androidhttpurlconnectionpostdata

提问by Rob

I've already created my HTTPUrlConnection :

我已经创建了我的 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 HttpPostinstead?

我不知道如何在 http 正文中设置 postData。怎么做?我会更好地使用HttpPost吗?

Thanks for your help.

谢谢你的帮助。

回答by Maxim Shoustin

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:

但是,如果您想以 Json 形式发送,请将内容类型更改为:

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

and now our strwe can write:

现在str我们可以写:

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

Hope it will help,

希望它会有所帮助,

回答by PopulusTremuloides

Guruparan's linkin 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:

上面评论中Guruparan 的链接为这个问题提供了一个非常好的答案。我强烈建议看一下。这是使他的解决方案起作用的原则:

From what I understand, the HttpURLConnection represents the response body as an OutputStream. So you need to call something like:

据我了解,HttpURLConnection 将响应主体表示为 OutputStream。所以你需要调用类似的东西:

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

然后继续使用连接(您仍然需要关闭)。