使用HttpURLConnection的Android POST请求

我正在尝试使用HttpURLConnection执行post请求,但不知道如何正确执行.

我可以使用以下代码成功执行AndroidAsyncHttp客户端的请求:

AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.addHeader("Content-type", "application/json");
httpClient.setUserAgent("GYUserAgentAndroid");
String jsonParamsString = "{\"key\":\"value\"}";
RequestParams requestParams = new RequestParams("request", jsonParamsString);
httpClient.post("<server url>", requestParams, jsonHttpResponseHandler);

在桌面计算机上使用curl可以执行相同的请求:

curl -A "GYUserAgentAndroid" -d 'request={"key":"value"}' '<server url>'

这两种方法都给了我服务器的预期响应.

现在我想使用HttpURLConnection做同样的请求.问题是我不知道如何正确地做到这一点.
我尝试过这样的事情:

URL url = new URL("<server url>");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("User-Agent", "GYUserAgentAndroid");
httpUrlConnection.setRequestProperty("Content-Type", "application/json");
httpUrlConnection.setUseCaches (false);

DataOutputStream outputStream = new DataOutputStream(httpUrlConnection.getOutputStream());

// what should I write here to output stream to post params to server ?

outputStream.flush();
outputStream.close();

// get response
InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
    stringBuilder.append(line);
}
responseStreamReader.close();

String response = stringBuilder.toString();
JSONObject jsonResponse = new JSONObject(response);
// the response is not I'm expecting

return jsonResponse;

如何正确地将与AsyncHttpClient和curl的工作示例中的数据相同的数据写入HttpURLConnection输出流?

提前致谢.

解决方法:

您可以使用以下内容发布参数

outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();
上一篇:为URLConnection设置“User-Agent”参数,以便从Java应用程序查询Google


下一篇:java – 在Perl中是否有类似于HttpURLConnection的东西?