title: Android: doPost to server does not work
body: <p>I want to create an Android app that process some data, gives output as array and sends this output to server. To do this, I make processing and sending in AsyncTask.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>//Params, progress, result
  public class MachineLearningTask extends AsyncTask&lt;Integer, String, int[]&gt;{
  
  public interface TaskListener {
      public void onFinished(int[] result);
  }
  
  private final static String TARGET_URL = "http://myURL";
  private final static String CHARSET = "UTF-8";
  
  private TaskListener taskListener;
  
  private Context context;
  private final ProgressDialog dialog;
  private String activityTest;
  
  public MachineLearningTask(Context ctx, String activity, TaskListener listener) {
      context = ctx;
      dialog = new ProgressDialog(context);
      taskListener = listener;
      activityTest = activity;
  }
  
  protected void onPreExecute() {
      this.dialog.setMessage("Processing...");
      this.dialog.show();
  
  }
  
  @Override
  protected int[] doInBackground(Integer... params) {
  
      // K-Means
      KMeansClustering kmeans = new KMeansClustering(params[0]);
      kmeans.mainKmeans();
  
      // K-NN
      KnnClustering knn = new KnnClustering();
  
      KmeansAndKnnAnalysis kka = new KmeansAndKnnAnalysis();
      kka.doAnalysis(kmeans,knn);
  
      int[] occurrenceKMeans = kka.getKmeansOccurrenceArray();
      int[] occurrenceKnn = kka.getKnnOccurrenceArray();
  
      // Google e Most
      GoogleAndMostAnalysis gma = new GoogleAndMostAnalysis();
      gma.Google_Most_Recognized_Activity();
      int[] occurrenceGoogle = gma.getGoolgeRecognizedActivity();
      int[] occurrenceMost = gma.getMostRecognizedActivity();
  
      FileOperation fo = new FileOperation();
      fo.writeResult(activityTest, occurrenceKMeans, occurrenceKnn, occurrenceGoogle, occurrenceMost);
  
      int idActivityKMeans = gma.findMax(occurrenceKMeans);
      int idActivityKnn = gma.findMax(occurrenceKnn);
      int idActivityGoogle = gma.findMax(occurrenceGoogle);
      int idActivityMost = gma.findMax(occurrenceMost);
  
      int[] matrixOccurrence = {idActivityKMeans, idActivityKnn, idActivityGoogle, idActivityMost};
  
      JSONObject dataToSend = algorithmFeedback(matrixOccurrence);
      JSONObject test = doFunc(dataToSend);
  
      Log.d("HTTP_POST", dataToSend.toString());
  
      return matrixOccurrence;
  }
  
  @SuppressLint("NewApi")
  protected void onPostExecute(int[] result) {
  
      if (dialog.isShowing()) {
          dialog.dismiss();
      }
      if (taskListener != null) {
          taskListener.onFinished(result);
      } else {
          Toast.makeText(context, "Fail!", Toast.LENGTH_SHORT).show();
      }
  }
  
  /* {"result":[
                  {"algorthm":"Kmeans", "readAct":"camminare", "trueAct":"camminare"},
                  {"algorthm":"Knn", "readAct":"camminare", "trueAct":"camminare"},
                  {"algorthm":"Google", "readAct":"camminare", "trueAct":"camminare"},
                  {"algorthm":"Most", "readAct":"camminare", "trueAct":"camminare"}
              ]}*/
  private JSONObject algorithmFeedback(int[] result){
  
      FileOperation fo = new FileOperation();
      String algorithm;
      String knowActivity;
      JSONObject obj = new JSONObject();
      JSONArray array = new JSONArray();
      JSONObject item;
  
      try{
  
          for (int i = 0 ; i&lt;result.length; i++){
              item = new JSONObject();
              algorithm = fo.getAlgorithmByIndex(i);
              knowActivity = fo.idToActivity(result[i], algorithm);
              item.put("algorithm", algorithm);
              item.put("readAct", knowActivity);
              item.put("trueAct", activityTest);
              array.put(item);
          } 
              obj.put("result", array);
  
      } catch (JSONException e) {
          e.printStackTrace();
      }
      return obj;
  }
  
  private Boolean checkNetworkConnection(){
      ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
      if (networkInfo != null &amp;&amp; networkInfo.isConnected()) {
          return true;
      } else {
          //Non è possibile connettersi
          return false;
      }
  }
  
  private JSONObject doFunc(JSONObject params) {
      JSONObject serverResponse = null;
  
      if(checkNetworkConnection() == true) {
          Log.d("OK", "OK");
          URL url = null;
          HttpURLConnection urlConnection = null;
  
          try {
              url = new URL(TARGET_URL);
              urlConnection = (HttpURLConnection) url.openConnection();
              Log.d("OK1", "OK1");
              //To upload data to a web server, configure the connection for output using setDoOutput(true).
              urlConnection.setDoOutput(true);
              urlConnection.setRequestMethod("POST");
              urlConnection.setRequestProperty("Accept-Charset", CHARSET);
              urlConnection.setRequestProperty("Content-Type", "application/json; charset="+CHARSET);
              Log.d("OK2", "OK2");
              //For best performance, you should call either setFixedLengthStreamingMode(int) 
              //when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. 
              urlConnection.setChunkedStreamingMode(0);
  
              //------------Request-----------
              OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
              writeStream(out, params);
              Log.d("OK3", "OK3");
              //-----------Response----------
              InputStream in = new BufferedInputStream(urlConnection.getInputStream());
              serverResponse = readStream(in);
              Log.d("OK4", "OK4");
          } catch (MalformedURLException e) {
                  e.printStackTrace();
                  serverResponse = null;
          } catch (IOException e) {
                  e.printStackTrace();
                  serverResponse = null;
          } finally {
               urlConnection.disconnect();
          }
      }
  
      return serverResponse;
  }
  
  private void writeStream(OutputStream out, JSONObject obj){
      String clientData = obj.toString();
      try {
          out.write(clientData.getBytes(CHARSET));
          out.flush();
          out.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  
  private JSONObject readStream(InputStream in) {
      String serverResponse = in.toString();
      JSONObject out = null;
  
      try {
          in.close();
          out = new JSONObject(serverResponse);
      } catch (IOException e) {
          e.printStackTrace();
          out = null;
      } catch (JSONException e) {
          e.printStackTrace();
          out = null;
      }
  
      return out;
  }
  }
  </code></pre>
  
  <p>When i run this app, it works fine until this line of code:</p>
  
  <pre><code>Log.d("OK2", "OK2");
  </code></pre>
  
  <p>After this point, the app shows the ProgressDialog and does not do anything. 
  After one minute the app crashes.</p>
  
  <p>Here there is a part of stack trace:</p>
  
  <pre><code>11-27 20:05:39.921: D/OK(28449): OK
  11-27 20:05:39.924: D/OK1(28449): OK1
  11-27 20:05:39.925: D/OK2(28449): OK2
  11-27 20:05:39.931: I/System.out(28449): (HTTPLog)-Static: isSBSettingEnabled false
  11-27 20:05:39.924: I/System.out(28449): (HTTPLog)-Static: isSBSettingEnabled false
  11-27 20:06:40.654: I/Timeline(28449): Timeline: Activity_idle id: android.os.BinderProxy@c079afe time:13153897
  11-27 20:07:11.384: V/ActivityThread(28449): updateVisibility : ActivityRecord{8b423d2 token=android.os.BinderProxy@c079afe {org.most/com.unipa.activityrecognition.Experiment}} show : true
  11-27 20:07:12.594: D/ViewRootImpl(28449): MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
  11-27 20:07:49.004: W/System.err(28449): java.net.ConnectException: failed to connect to /192.168.1.4 (port 8080): connect failed: ETIMEDOUT (Connection timed out)
  11-27 20:07:49.004: W/System.err(28449):    at libcore.io.IoBridge.connect(IoBridge.java:124)
  11-27 20:07:49.004: W/System.err(28449):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
  11-27 20:07:49.004: W/System.err(28449):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
  11-27 20:07:49.004: W/System.err(28449):    at java.net.Socket.connect(Socket.java:884)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:434)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:105)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.Connection.connect(Connection.java:1331)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1410)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:466)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:447)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:353)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
  11-27 20:07:49.004: W/System.err(28449):    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
  11-27 20:07:49.004: W/System.err(28449):    at com.unipa.algorithm.MachineLearningTask.doFunc(MachineLearningTask.java:195)
  11-27 20:07:49.004: W/System.err(28449):    at com.unipa.algorithm.MachineLearningTask.doInBackground(MachineLearningTask.java:101)
  11-27 20:07:49.004: W/System.err(28449):    at com.unipa.algorithm.MachineLearningTask.doInBackground(MachineLearningTask.java:1)
  11-27 20:07:49.004: W/System.err(28449):    at android.os.AsyncTask$2.call(AsyncTask.java:295)
  11-27 20:07:49.004: W/System.err(28449):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  11-27 20:07:49.004: W/System.err(28449):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
  11-27 20:07:49.004: W/System.err(28449):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  11-27 20:07:49.004: W/System.err(28449):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  11-27 20:07:49.004: W/System.err(28449):    at java.lang.Thread.run(Thread.java:818)
  11-27 20:07:49.004: W/System.err(28449): Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
  11-27 20:07:49.004: W/System.err(28449):    at libcore.io.Posix.connect(Native Method)
  11-27 20:07:49.004: W/System.err(28449):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
  11-27 20:07:49.004: W/System.err(28449):    at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
  11-27 20:07:49.004: W/System.err(28449):    at libcore.io.IoBridge.connect(IoBridge.java:122)
  11-27 20:07:49.004: W/System.err(28449):    ... 24 more
  11-27 20:07:49.004: D/HTTP_POST(28449): {"result":[{"algorithm":"KMEANS","readAct":"Fermo","trueAct":"Fermo"},{"algorithm":"KNN","readAct":"Fermo","trueAct":"Fermo"},{"algorithm":"GOOGLE","readAct":"still","trueAct":"Fermo"},{"algorithm":"MOST","readAct":"staticoSulTavolo","trueAct":"Fermo"}]}
  11-27 20:07:49.014: D/ViewRootImpl(28449): #3 mView = null
  11-27 20:07:49.014: D/Occurrence(28449): [0, 0, 0, 0]
  11-27 20:07:56.264: I/Timeline(28449): Timeline: Activity_idle id: android.os.BinderProxy@c079afe time:13229504
  </code></pre>
  
  <p>Can you help me to find where i'm wrong?</p>
  
  <p><strong>Solution:</strong></p>
  
  <p><strong>The problem is that <em>Windows firewall blocks the port</em> where i try to connect.<br>
  For this reason the connection is in time out. 
  To resolve this problem in Windows just create an exception in Windows firewall.</strong></p>