我正在 android 中创建一个 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 并将其写入OutputStream
连接的
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) {}
}
当我发出请求时,我的状态为 500,因为我的服务器收到一个空的 POST 数据,它是无效的 json。
在 Web 浏览器和 curl 上也是如此。GET 在具有相同参数的 android 上工作。我错过了什么?应该为 POST 请求设置的方式参数的顺序有问题吗?