Android的HTTPUrlConnection:如何设置发布数据在http身上?

我已经创build了我的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吗?

谢谢你的帮助。

如果你想发送string只能尝试这种方式:

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

但是,如果您想将Json更改内容types发送到:

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

现在我们可以写:

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

希望这会有所帮助,