使用HttpURLConnection进行Android POST请求

5
我正在尝试使用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输出流中?
提前致谢。
3个回答

5
    public String getJson(String url,JSONObject params){
    try {
        URL _url = new URL(url);
        HttpURLConnection urlConn =(HttpURLConnection)_url.openConnection();
        urlConn.setRequestMethod(POSTMETHOD);
        urlConn.setRequestProperty("Content-Type", "applicaiton/json; charset=utf-8");
        urlConn.setRequestProperty("Accept", "applicaiton/json");
        urlConn.setDoOutput(true);
        urlConn.connect();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        writer.write(params.toString());
        writer.flush();
        writer.close();

        if(urlConn.getResponseCode() == HttpURLConnection.HTTP_OK){
            is = urlConn.getInputStream();// is is inputstream
        } else {
            is = urlConn.getErrorStream();
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        response = sb.toString();
        Log.e("JSON", response);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return response ;

}

2
您可以使用以下内容来提交参数。
outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();

1
不幸的是,这并没有帮助到我。在curl中,我将post数据指定为-d 'request=<json object>'。我认为,这个参数“request”应该以某种方式写入输出流中。但我不知道如何正确地做到这一点。 无论如何,谢谢。 - pvshnik
2
使用 outputStream.writeBytes("request=" + jsonParamsString); - Sunil Mishra
谢谢。现在服务器识别“请求”参数了。看起来它现在无法正确解析JSON对象。希望我能找到解决方案。 - pvshnik

0

这里有一个使用HttpUrlConnection的请求,你所缺少的就是从服务器读取值。

try {
    JSONObject job = new JSONObject(log);
    String param1 = job.getString("AuditScheduleDetailID");
    String param2 = job.getString("AuditAnswerId");
    String param3 = job.getString("LocalFindingID");
    String param4 = job.getString("LocalMediaID");
    String param5 = job.getString("Files");
    String param6 = job.getString("ExtFiles");
    Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
            "pertama");

    URL url = new URL("myurl");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    conn.setRequestProperty("Accept", "application/json");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("AuditScheduleDetailID", param1);
    jsonParam.put("AuditAnswerId", param2);
    jsonParam.put("LocalFindingID", param3);
    jsonParam.put("LocalMediaID", param4);
    jsonParam.put("Files", param5);
    jsonParam.put("ExtFiles", param6);

    Log.i("JSON", jsonParam.toString());
    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
    //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
    os.writeBytes(jsonParam.toString());

    os.flush();
    os.close();
    InputStream is = null;

    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            is = conn.getInputStream();// is is inputstream
        } else {
            is = conn.getErrorStream();
        }


        try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        String response = sb.toString();
        //HERE YOU HAVE THE VALUE FROM THE SERVER
        Log.d("Your Data", response);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }


    conn.disconnect();
} catch (JSONException | IOException e) {
    e.printStackTrace();
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接