Android HTTPUrlConnection:如何在HTTP正文中设置POST数据?

55

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

谢谢您的帮助。


你想发送Json数据吗? - Maxim Shoustin
1
@MaximShoustin 我不能直接将它发送为字符串吗?在iOS中,我通常会这样做:NSString *string = @"x=val1&y=val2"; NSData *postData = [string dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO]; [request setHTTPBody:postData]; - Rob
@Rob,你好,我想和你谈谈在Android中向POST请求添加参数的问题。 - Pankaj Nimgade
2个回答

86

如果你只想发送字符串,请尝试这种方法:

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

但如果你想以Json的格式发送,请将内容类型更改为:

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

现在我们可以这样编写str

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

希望能对您有所帮助,


1
在键名中使用单引号是无效的JSON格式。:p - Julien Palard
@JulienPalard 谢谢,已修复。 - Maxim Shoustin
6
这里是完整的例子 :) http://guruparang.blogspot.com/2016/01/example-on-working-with-json-and.html - Guruparan Giritharan
谢谢,这很不错。 - Sukhbir

4

我强烈推荐看一下上面评论中的Guruparan的链接,他提供了一个非常好的解决方案。这是让他的解决方案起作用的原则:

据我所知,HttpURLConnection将响应体表示为OutputStream。因此,您需要调用以下类似的内容:

获取连接的输出流

OutputStream op = conn.getOuputStream();

写响应体
op.write( [/*your string in bit form*/] );

关闭输出流

op.close();

然后您可以继续连接(仍需关闭)并愉快地进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接