2
我創建android的一個HttpURLConnection類,並準備好應對後如下圖所示HTTP POST HTTPUrlConnection中的數據未設置?
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("content-type", "application/json");
byte [] encoded = Base64.encode((username+":"+password).getBytes("UTF-8"), Base64.DEFAULT);
//Basic Authorization
urlConnection.setRequestProperty("Authorization", "Basic "+ new String(encoded, "UTF-8"));
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//This gets implicitly set when DoOutput is True, but still let it be
urlConnection.setRequestMethod("POST");
//Required for POST not to return 404 when used on with a host:port combination
//http://stackoverflow.com/questions/5379247/filenotfoundexception-while-getting-the-inputstream-object-from-httpurlconnectio
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0");
urlConnection.setRequestProperty("Accept","*/*");
然後,我準備JSON,並將其寫入到連接
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
outputStreamWriter = urlConnection.getOutputStream();
outputStreamWriter.write(jsonObject.toString().getBytes());
finally {
if (outputStreamWriter != null) try { outputStreamWriter.close(); } catch (IOException logOrIgnore) {}
}
的OutputStream
當我這樣做請求,我得到500的狀態,因爲我的服務器收到一個空的POST數據,這是無效的json。
從Web瀏覽器和捲曲相同的作品。 GET在Android上使用相同的參數。我錯過了什麼? POST請求應該設置的參數方式的順序有問題嗎?
您的服務器是否收到請求的其餘部分? (auth,用戶代理?) – njzk2 2013-03-22 14:01:50
<使用權限android:name =「android.permission.INTERNET」/> – 2013-03-22 14:03:16
@ njzk2 - 是的,它確實 – 2013-03-22 14:08:27