title: Using POST to send JSON object Asynchronously (android.os.NetworkOnMainThreadException)
body: <p>I am trying to send JSON using the http POST method to a web service. Additionally I am trying to make it asynchronous so it runs in a background thread on the android device.</p>
  
  <p>My problem is:</p>
  
  <p>I want to make this class generic so I can send any JSON object. I added another parameter to sendHTTPData(String url, JSONObject json). In order for this to run in a background thread I must explicitly override doInBackground.</p>
  
  <p>If I explicitly override doInBackground, how do I pass my JSON object in to this generic method.</p>
  
  <p>When I do run sendHTTPData on its own I get android.os.NetworkOnMainThreadException.</p>
  
  <p>Code:</p>
  
  <pre><code>    public class SendHttpDataAsync extends AsyncTask&lt;String, Void,  String&gt; {
      private static final String TAG = "SendHttpDataAsync";
  
      @Override
      protected String doInBackground(String... urls) {
          return sendHTTPData(urls[0], MY_JSON_OBJECT);
      }
  
      public String sendHTTPData(String url, JSONObject json) {
          HttpURLConnection connection = null;
          try {
              URL object=new URL(url);
              connection = (HttpURLConnection) object.openConnection();
  
              connection.setDoOutput(true);
              connection.setDoInput(true);
              connection.setRequestMethod("POST");
              connection.setRequestProperty("Content-Type", "application/json");
              connection.setRequestProperty("Accept", "application/json");
  
              OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
  
              streamWriter.write(json.toString());
              streamWriter.flush();
  
              StringBuilder stringBuilder = new StringBuilder();
  
              if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                  InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
                  BufferedReader bufferedReader = new BufferedReader(streamReader);
  
                  String response = null;
                  while ((response = bufferedReader.readLine()) != null) {  
                      stringBuilder.append(response + "\n");  
                  }  
                  bufferedReader.close();  
  
                  Log.d(TAG, stringBuilder.toString());
                  return stringBuilder.toString();
              } else {
                  Log.e(TAG, connection.getResponseMessage());
                  return null;
              }   
          } catch (Exception exception){
              Log.e(TAG, exception.toString());
              return null;
          } finally {
              if (connection != null){
                  connection.disconnect();
              }
          }
      }
  }
  </code></pre>