为Android创建HttpResponse超时

时间:2015-06-09 22:43:37

标签: android http

你好我之前从未使用过HttpResponses,我希望能够在3分钟后断开网络连接,因为用户失去了与网络的连接。是否有完整的代码,我可以看到这样的事情?

2 个答案:

答案 0 :(得分:0)

我知道两种可能的方法:

  1. 使用DefaultHttpClient的最简单方法,已在isma3l推荐link中解释:
  2. 这样的事情:

    private DefaultHttpClient httpClient;
    // set connection timeout to 1 second
    HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
    // set socket timeout to 1 second
    HttpConnectionParams.setSoTimeout(httpParameters, 1000);
    httpClient = new DefaultHttpClient(httpParameters);
    /* === and then, use your httpClient to perform your operations... === */
    
    1. 硬核方式:通过使用处理程序调用另一个线程中的Http操作来手动处理与线程/处理程序的连接,以接收其回调。在处理程序中,您调用postDelayed方法作为参数传递一个Runnable来处理超时。
    2. 这样的事情:

      // create a handler to load content
      private final Runnable loadContent = new Runnable() {
          @Override
          public void run() {
              /* === CALL HTTP AND PROCESS IT HERE === */
              // remove the timeout runnable after receiving http response
              handler.removeCallbacks(timeoutRunnable);
          }
      }
      // create a handler to handle timeout
      private final Runnable timeoutRunnable = new Runnable() {
          @Override
          public void run() {
              handler.sendEmptyMessage(1);
          }
      };
      // create a handler to handle the connection
      private final Handler handler = new Handler() {
          @Override
          public void handleMessage(Message msg) {
              switch (msg.what) {
                  case 1: // timeout
                      handler.removeCallbacks(timeoutRunnable);
                      break;
                  /* === OTHER MESSAGES TO HANDLE OTHER SITUATIONS === */
              }
          }
      };
      // call the connection inside a new thread
      private void createNewLoader() {
          // create a delayed runnable with a timeout of 1 second
          handler.postDelayed(timeoutRunnable, 1000);
          // call the content loader
          new Thread(loadContent).start();
      }
      

      希望它有所帮助。

答案 1 :(得分:0)

请勿使用DefaultHttpClient,Google已将其弃用,停止支持,并建议使用速度更快的URLConnection。超时处理如下:

// Prepare connection
URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(TIMEOUT);
conn.setReadTimeout(TIMEOUT);