I execute a post request in another thread using AsyncTask, while it is executed, the progress bar is spinning, I turn off the application, turn off the wifi, the application crashes! Interested in 2 questions, is it possible to monitor the presence of a connection in real time and how to interrupt the request?

protected Void doInBackground (String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(УРЛ); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("login", "майлогин")); nameValuePairs.add(new BasicNameValuePair("pass", "майпасс")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); String str = new String(); str = EntityUtils.toString(response.getEntity()); publishProgress(str); } catch (ClientProtocolException e) { } catch (IOException e) { Toast.makeText(SigiActivity.this, "Ошибка : " + e.getMessage(), Toast.LENGTH_LONG).show(); } return null; } 
  • In the sense of? what cURL`om? - johniek_comp
  • I did not understand the question - katso
  • And I am yours. How can I send a request and it suddenly ends? - johniek_comp 7:09 pm
  • Are you talking about the program in general? or do you write it yourself? in debager you can - Gorets

2 answers 2

You can monitor the presence of a connection to a Wi-Fi or network operator (connecting to the network does not mean Internet accessibility!). But in your case I do not see the need for it. If the Internet disappears during the execution of the request, an IOException will be thrown - you just need to catch it and process it correctly.

I see a block in your code

 } catch (IOException e) { Toast.makeText(SigiActivity.this, "Ошибка : " + e.getMessage(), Toast.LENGTH_LONG).show(); } 

Toast refers to the UI, and no code that works with the UI should be called from the doInBackground method. Most likely because of this, the application crashes.

It will be correct in the doInBackground method to return a result containing a sign of the success of the request and / or other relevant data, and in the onPostExecution method put out the code that gives something to the screen depending on the result of the request.

  • Earned! Grateful! - katso

Did you look at the debugger? Most likely you do not have HTTP error handling. Show at least the code so that you can give you more detailed tips. Or wrap the POST transfer function in try-catch yourself.

  • I can not reproduce the error on the emulator, it happens on a physical device! - katso
  • one
    Put aLogCat from the market or connect the device to the computer via usb and watch logcat right in the eclipse. - Yura Ivanov