2 baifaxiaoyao baifaxiaoyao 于 2012.09.18 15:16 提问

使用Java,如何给Android设置 HttpResponse超时?

为了检查网络连接的情况,我创建了下边的方法:

private void checkConnectionStatus() {
    HttpClient httpClient = new DefaultHttpClient();

    try {
      String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
                   + strSessionString + "/ConnectionStatus";
      Log.d("phobos", "performing get " + url);
      HttpGet method = new HttpGet(new URI(url));
      HttpResponse response = httpClient.execute(method);

      if (response != null) {
        String result = getResponse(response.getEntity());
        ...

当我关闭服务器来测试执行的时候,需要等待很长的时间

HttpResponse response = httpClient.execute(method);

有人知道怎么设置超时来避免等待太长的时间吗?
谢谢!

3个回答

yizhenbeifeng
yizhenbeifeng   2012.09.18 15:36
已采纳

在我的示例中有两个超时的设置。连接超时声明抛出异常"java.net.SocketTimeoutException: Socket is not connected",Socket超时是"java.net.SocketTimeoutException: The operation timed out".

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

如果你想给任何存在的HTTPClient(如DefaultHttpClient 或AndroidHttpClient)设置参数,你可以使用 setParams()方法。

httpClient.setParams(httpParameters);
niangzhi
niangzhi   2012.09.18 15:57

如果你使用Jakarta的http client library ,那么你可以这样做:

   HttpClient client= new HttpClient();
    client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(5000));
    client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000));
   GetMethod method= new GetMethod("http://www.yoururl.com");
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(5000));
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
   int statuscode= client.executeMethod(method);
oSanYeCao1234567
oSanYeCao1234567   Ds   Rxr 2016.10.10 18:24

HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

Csdn user default icon
上传中...
上传图片
插入图片