Android POST request using HttpURLConnection
Asked Answered
P

3

5

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

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);

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.

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;

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

Thanks in advance.

Propertied answered 29/11, 2013 at 5:49 Comment(0)
G
2

You can use the following to post the params

outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();
Gurglet answered 29/11, 2013 at 6:33 Comment(3)
Unfortunately, this does not helped me. In curl I specify post data as -d 'request=<json object>'. I think, this parameter "request" should be somehow written in output stream. But I don't know how to do it correctly. Anyway, thank you.Propertied
Use outputStream.writeBytes("request=" + jsonParamsString);Gurglet
Thank you. Now server recognise "request" parameter. It seems that it can't properly parse json object now. Hope, I'll find solution for this.Propertied
W
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 ;

}
Wraparound answered 17/10, 2015 at 7:15 Comment(0)
G
2

You can use the following to post the params

outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();
Gurglet answered 29/11, 2013 at 6:33 Comment(3)
Unfortunately, this does not helped me. In curl I specify post data as -d 'request=<json object>'. I think, this parameter "request" should be somehow written in output stream. But I don't know how to do it correctly. Anyway, thank you.Propertied
Use outputStream.writeBytes("request=" + jsonParamsString);Gurglet
Thank you. Now server recognise "request" parameter. It seems that it can't properly parse json object now. Hope, I'll find solution for this.Propertied
R
0

Here you have a request using HttpUrlConnection, what you were missing was just read the value from the server.

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();
} 
Royo answered 24/11, 2017 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.