Android POST request using HttpURLConnection

android, curl, httpurlconnection, outputstream, post

Solution

You can use the following to post the params

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

Problem

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.

Original source