How should I handle server timeouts and error code responses to an http post in Android App?

后端 未结 3 1709
灰色年华
灰色年华 2021-02-04 18:25

My Android App does http posts to URLs like http://example.com/abc.php?email=abc@xyz.com So the Android App basically talks to PHPs on the server side and receives JSON response

3条回答
  •  北海茫月
    2021-02-04 18:49

    Adding to the very good suggestions so far...

    My work associate taught me to use classes from the org.apache.http package like this:

    String result = null;
    HttpGet request = new HttpGet(some_uri);
    
    // As Jeff Sharkey does in the android-sky example, 
    // use request.setHeader to optionally set the User-Agent header.
    
    HttpParams httpParams = new BasicHttpParams();
    int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
    HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
    HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
    HttpClient client = new DefaultHttpClient(httpParams);
    
    try
    {
      HttpResponse response = client.execute(request);
      StatusLine status = response.getStatusLine();
      if (status.getStatusCode() == HttpStatus.SC_OK)
      {
        ResponseHandler responseHandler = new BasicResponseHandler();
        result = responseHandler.handleResponse(response);
      }
      else
      {
        // Do something else, if wanted.
      }
    }
    catch (ClientProtocolException e)
    {
      Log.e(LOG_TAG, "HTTP Error", e);
      // Do something else, if wanted.
    }
    catch (IOException e)
    {
      Log.e(LOG_TAG, "Connection Error", e);
      // Do something else, if wanted.
    }
    finally
    {
      client.getConnectionManager().shutdown();
    }
    
    // Further parse result, which may well be JSON.

提交回复
热议问题