Android POST请求使用HttpURLConnection [英] Android POST request using HttpURLConnection

查看:175
本文介绍了Android POST请求使用HttpURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用HttpURLConnection执行后期请求,但不知道如何正确执行。

I'm trying to execute post request using HttpURLConnection but don't know how to do it correctly.

我可以使用 AndroidAsyncHttp 客户端使用以下代码:

I can successfully execute request with AndroidAsyncHttp client using following code:

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执行相同的请求:

The same request can be performed using curl on desktop machine:

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

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

Both of this methods give me expected response from server.

想使用HttpURLConnection做同样的请求。问题是我不知道如何正确地做。
我试过这样:

Now I want to do the same request using HttpURLConnection. The problem is I don't know how to do it correctly. I've tried something like this:

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;


$ b。

How to correctly write the same data as in working examples with AsyncHttpClient and curl to the HttpURLConnection output stream?

提前感谢。

推荐答案

post the params

You can use the following to post the params

outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();

这篇关于Android POST请求使用HttpURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆