title: httpresponse resp= httpClient.execute(httpPost) hangs in uploading file from android to webservice(wcf)
body: <p>I am using android code given below in a service (subclass of IntentService) with it's saparate thread but this code works sometimes cool but sometimes not. That means reliability issue. after debuging I found that code hangs sometimes at httpClient.execute(httppost). How can I make it accurate to work in any condition? Thanks in advance.                </p>
  
  <p>httpresponce code </p>
  
  <pre><code>final HttpResponse resp;
              final HttpClient httpClient = new DefaultHttpClient();      
              HttpPost httpPost = new HttpPost(serverUrl);
  
              try {
                  ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(file_uri, "r");
                  InputStream in = context.getContentResolver().openInputStream(file_uri);
                  CountingInputStreamEntity entity = new CountingInputStreamEntity(in, fileDescriptor.getStatSize());
                  entity.setUploadListener(this);
                  entity.setContentType("application/gpx+xml");
                  //entity.setContentType("binary/octet-stream");
                  httpPost.setEntity(entity);
              } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              try {
                  Log.i("FOO", "About to call httpClient.execute");
                  resp = httpClient.execute(httpPost);
                  if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                      notification.setLatestEventInfo(context, "Uploading Completed", no_rx+" Rx Uploaded", contentIntent);
                      no_rx = 0;
                      notification.flags |= Notification.FLAG_AUTO_CANCEL;
                      notificationManager.notify(1, notification);
                      Log.i("FOO", "All done");
                  } else {
                      Log.i("FOO", "Screw up with http - " + resp.getStatusLine().getStatusCode());
                  }
                  resp.getEntity().consumeContent();
              } catch (ClientProtocolException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
  </code></pre>
  
  <p>complete code</p>
  
  <pre><code>public class UploadService extends IntentService{
  
      private NotificationManager notificationManager;
      private Notification notification;
  
      public UploadService(String name) {
          super(name);
      }
  
      public UploadService(){
          super("UploadService");
      }
  
  
      @Override
      protected void onHandleIntent(Intent intent) {
          notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
          //Uri uri  = intent.getData();
          String[] all_path_sel = intent.getStringArrayExtra("all_path_sel");
          for(String s : all_path_sel){
              File f = new File(s);
              Uri file_uri = Uri.fromFile(f);         
              String serverUrl = Constants.BASIC_URL+Constants.ACTION_UPLOADFILE
                      +LoginActivity.user.getUserUniqueId()+"/"+f.getName();
              Thread t = new Thread(new BackgroundThread(this, file_uri,serverUrl));
              t.start();          
              try {
                  t.join();
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
  
      }
  
      int no_rx = 0;
      private class BackgroundThread implements Runnable, CountingInputStreamEntity.UploadListener {
  
          Context context;
          Uri file_uri;
          String serverUrl;
          int lastPercent = 0;
  
  
          public BackgroundThread(Context context, Uri file_uri,String serverUrl) {
              this.context = context;
              this.file_uri = file_uri;
              this.serverUrl = serverUrl;
          }
  
          @Override
          public void run() {
              no_rx++;
              Intent notificationIntent = new Intent();
              PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
  
  
              notification = new Notification(R.drawable.ic_launcher,
                      "Uploading Rx "+no_rx, System.currentTimeMillis());
              notification.flags = notification.flags
                      | Notification.FLAG_ONGOING_EVENT;
              notification.contentView = new RemoteViews(getApplicationContext()
                      .getPackageName(), R.layout.upload_progress_bar);
              notification.contentIntent = contentIntent;
              notification.contentView.setProgressBar(R.id.progressBar1, 100,0, false);
  
              notificationManager.notify(1, notification);
  
              Log.i("FOO", "Notification started");
  
              final HttpResponse resp;
              final HttpClient httpClient = new DefaultHttpClient();      
              HttpPost httpPost = new HttpPost(serverUrl);
  
              try {
                  ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(file_uri, "r");
                  InputStream in = context.getContentResolver().openInputStream(file_uri);
                  CountingInputStreamEntity entity = new CountingInputStreamEntity(in, fileDescriptor.getStatSize());
                  entity.setUploadListener(this);
                  entity.setContentType("application/gpx+xml");
                  //entity.setContentType("binary/octet-stream");
                  httpPost.setEntity(entity);
              } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              try {
                  Log.i("FOO", "About to call httpClient.execute");
                  resp = httpClient.execute(httpPost);
                  if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                      notification.setLatestEventInfo(context, "Uploading Completed", no_rx+" Rx Uploaded", contentIntent);
                      no_rx = 0;
                      notification.flags |= Notification.FLAG_AUTO_CANCEL;
                      notificationManager.notify(1, notification);
                      Log.i("FOO", "All done");
                  } else {
                      Log.i("FOO", "Screw up with http - " + resp.getStatusLine().getStatusCode());
                  }
                  resp.getEntity().consumeContent();
              } catch (ClientProtocolException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
  
  
          @Override
          public void onChange(int percent) {
              if(percent &gt; lastPercent) {
                  notification.contentView.setProgressBar(R.id.progressBar1, 100, percent, false);
                  notificationManager.notify(1, notification);
                  lastPercent = percent;
              }
          }
  
      }
  
  }
  </code></pre>
  
  <p>Activity Code </p>
  
  <pre><code>@Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_image_picker);
          setTitle("");
          initImageLoader();//load image in imageviewer
          init();
  
          if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.FROYO) {
              mCamera.mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
          } else {
              mCamera.mAlbumStorageDirFactory = new BaseAlbumDirFactory();
          }
  
      }
  
  private void initImageLoader() {
          DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                  .cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                  .bitmapConfig(Bitmap.Config.RGB_565).build();
          ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
                  this).defaultDisplayImageOptions(defaultOptions).memoryCache(
                  new WeakMemoryCache());
  
          ImageLoaderConfiguration config = builder.build();
          imageLoader = ImageLoader.getInstance();
          imageLoader.init(config);
      }
  
      private void init() {       
          gridGallery = (GridView) findViewById(R.id.gridGallery);
          gridGallery.setFastScrollEnabled(true);
          adapter = new ImageGridAdapter(getApplicationContext(), imageLoader);
          adapter.setMultiplePick(false);
          gridGallery.setAdapter(adapter);
          viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
          viewSwitcher.setDisplayedChild(1);                      
          mImageBitmap = null;        
          gridGallery.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
          gridGallery.setMultiChoiceModeListener(new MultiChoiceModeListener() {          
              @Override
              public boolean onActionItemClicked(android.view.ActionMode mode,
                      MenuItem item) {
                  // Respond to clicks on the actions in the CAB
                  switch (item.getItemId()) {
                      case R.id.delete_file:
                          SparseBooleanArray selected = adapter.getSelectedIds();
                          for (int i = (selected.size() - 1); i &gt;= 0; i--) {
                              if (selected.valueAt(i)) {
                                  ImageItem selecteditem = adapter.getItem(selected.keyAt(i));
                                  //adapter.remove(selecteditem);
                                  mImagePicker.remSelImage_updadr(selecteditem);
                              }
                          }
                          // Close CAB                        
                          mode.finish(); // Action picked, so close the CAB
                          return true;
                      default:
                          return false;
                  }               
              }
  
              @Override
              public boolean onCreateActionMode(android.view.ActionMode mode,
                      Menu menu) {
                  // Inflate the menu for the CAB
                  MenuInflater inflater = mode.getMenuInflater();
                  inflater.inflate(R.menu.context_file_picker, menu);
                  return true;
              }
  
              @Override
              public void onDestroyActionMode(android.view.ActionMode mode) {
                  adapter.removeSelection();
              }
  
              @Override
              public boolean onPrepareActionMode(android.view.ActionMode mode,
                      Menu menu) {
                  // TODO Auto-generated method stub
                  return false;
              }
  
              @Override
              public void onItemCheckedStateChanged(android.view.ActionMode mode,
                      int position, long id, boolean checked) {
                  final int checkedCount = gridGallery.getCheckedItemCount();
                  mode.setTitle(checkedCount + " Selected");
                  adapter.toggleSelection(position);
              }           
          });     
      }
  
      AlertDialog.Builder alert = new AlertDialog.Builder(ImagePickerActivity.this);
                  alert.setTitle(Constants.ALERT_FILEUPLOAD); 
                  alert.setMessage(Constants.ALERT_CONFIRMATION);
                  alert.setPositiveButton(Constants.ALERT_CONFIRMATION_OK, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {          
                      new Thread(){
                          public void run(){                  
                              mFileUploader = new FileUploader(mImagePicker.imgArLst);
                              mFileUploader.uploadFiles_withService();            
                          }
                      }.start();
                    }
                  });
  
          private class FileUploader{
              private ArrayList&lt;ImageItem&gt; imgArList;                         
  
              FileUploader(ArrayList&lt;ImageItem&gt; imgArList){
                  this.imgArList = imgArList;
              }
  
              private void uploadFiles_withService() {            
                  Intent intent = new Intent(ImagePickerActivity.this, UploadService.class);
                  ArrayList&lt;String&gt; arrStrLstPath = new ArrayList&lt;String&gt;();          
                  for(ImageItem im : mImagePicker.imgArLst){
                      String path = im.getSdCardPath();
                      arrStrLstPath.add(path);
                  }
                  String[] all_path_sel = arrStrLstPath.toArray(new String[arrStrLstPath.size()]);            
                  intent.putExtra("all_path_sel", all_path_sel);
                  startService(intent);
                  runOnUiThread(new Runnable(){
                      public void run(){
                          mImagePicker.clearAllImage_updadr();
                          //prgd.dismiss();
                      }
                  });         
                  }
              }               
          }
  </code></pre>