title: Android POST request using HttpURLConnection
body: <p>I'm trying to execute post request using HttpURLConnection but don't know how to do it correctly.</p>
  
  <p>I can successfully execute request with <a href="https://github.com/loopj/android-async-http" rel="noreferrer">AndroidAsyncHttp</a> client using following code:</p>
  
  <pre><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("&lt;server url&gt;", requestParams, jsonHttpResponseHandler);
  </code></pre>
  
  <p>The same request can be performed using curl on desktop machine:</p>
  
  <pre><code>curl -A "GYUserAgentAndroid" -d 'request={"key":"value"}' '&lt;server url&gt;'
  </code></pre>
  
  <p>Both of this methods give me expected response from server.</p>
  
  <p>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:</p>
  
  <pre><code>URL url = new URL("&lt;server url&gt;");
  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;
  </code></pre>
  
  <p>How to correctly write the same data as in working examples with AsyncHttpClient and curl to the HttpURLConnection output stream? </p>
  
  <p>Thanks in advance.</p>