Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android POST request using HttpURLConnection

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.

like image 601
pvshnik Avatar asked Nov 29 '13 05:11

pvshnik


People also ask

Is HttpURLConnection deprecated?

Deprecated. it is misplaced and shouldn't have existed. HTTP Status-Code 500: Internal Server Error.

Can I use HttpURLConnection for https?

HttpsURLConnection extends HttpURLConnection , and your connection is an instance of both. When you call openConnection() the function actually returns an HttpsURLConnection . However, because the https object extends the http one, your connection is still an instance of an HttpURLConnection .


2 Answers

    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 ;

}
like image 159
Nasz Njoka Sr. Avatar answered Sep 27 '22 18:09

Nasz Njoka Sr.


You can use the following to post the params

outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();
like image 38
Sunil Mishra Avatar answered Sep 27 '22 17:09

Sunil Mishra