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

Rob*_*Rob 52 android postdata 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);
Run Code Online (Sandbox Code Playgroud)

我不知道如何在http体中设置postData.怎么办?我会更好地使用HttpPost吗?

谢谢你的帮助.

Max*_*tin 79

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

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

但是如果你想以Json的形式发送更改内容类型:

conn.setRequestProperty("Content-Type","application/json");  
Run Code Online (Sandbox Code Playgroud)

现在str我们可以写:

String str =  "{\"x\": \"val1\",\"y\":\"val2\"}";
Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助,

  • 这里有完整的例子:) http://guruparang.blogspot.com/2016/01/example-on-working-with-json-and.html (6认同)