使用HttpURLConnection的Android POST请求

时间:2013-11-29 05:49:22

标签: android post curl httpurlconnection outputstream

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

我可以使用以下代码成功执行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 个答案:

答案 0 :(得分: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 ;

}

答案 1 :(得分:1)

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

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

答案 2 :(得分: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();
}