如何在Java中为Android设置HttpResponse超时

Nik*_*lin 332 java android timeout 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());
        ...
Run Code Online (Sandbox Code Playgroud)

当我关闭服务器进行测试时,执行会等待很长时间

HttpResponse response = httpClient.execute(method);
Run Code Online (Sandbox Code Playgroud)

有谁知道如何设置超时以避免等待太久?

谢谢!

kue*_*000 624

在我的示例中,设置了两个超时.连接超时抛出"java.net.SocketTimeoutException:Socket未连接"和套接字超时"java.net.SocketTimeoutException:操作超时".

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
Run Code Online (Sandbox Code Playgroud)

如果要设置任何现有HTTPClient的参数(例如DefaultHttpClient或AndroidHttpClient),可以使用函数setParams().

httpClient.setParams(httpParameters);
Run Code Online (Sandbox Code Playgroud)

  • @jellyfish - 尽管有文档,AndroidHttpClient确实_not_扩展DefaultHttpClient; 相反,它实现了HttpClient.您需要使用DefaultHttpClient来提供setParams(HttpParams)方法. (10认同)
  • 如果连接超时,HttpResponse会返回什么?一旦我的HTTP请求发出,然后我在调用返回时检查状态代码,但是如果调用已经超时,我在检查此代码时会得到NullPointerException ...基本上,我如何处理调用时的情况超时?(我给你的答案使用非常相似的代码) (3认同)
  • 嘿伙计们,不要错过这个优秀的答案.但是,我想在连接超时时向用户表示祝酒...我可以在连接超时时检测到任何方式吗? (3认同)
  • 不行.我在Sony和Moto上进行了测试,它们都被塞进去了. (2认同)

小智 13

要在客户端上设置设置:

AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
HttpConnectionParams.setSoTimeout(client.getParams(), 5000);
Run Code Online (Sandbox Code Playgroud)

我已经在JellyBean上成功使用了它,但也适用于旧平台....

HTH


Pab*_*ruz 8

如果您使用的是Jakarta的http客户端库,那么您可以执行以下操作:

        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);
Run Code Online (Sandbox Code Playgroud)

  • HttpClientParams.CONNECTION_MANAGER_TIMEOUT未知 (5认同)

Lea*_* ES 7

如果您使用的是默认的http客户端,请使用默认的http参数来执行此操作:

HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);
Run Code Online (Sandbox Code Playgroud)

最初的功劳归功于http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/


Dav*_*ias 5

对于那些说@ kuester2000的答案不起作用的人,请注意HTTP请求,首先尝试使用DNS请求查找主机IP,然后向服务器发出实际的HTTP请求,这样您可能还需要设置一个DNS请求超时.

如果您的代码在没有DNS请求超时的情况下工作,那是因为您可以访问DNS服务器或者您正在访问Android DNS缓存.顺便说一句,您可以通过重新启动设备来清除此缓存.

此代码扩展了原始答案,包括使用自定义超时的手动DNS查找:

//Our objective
String sURL = "http://www.google.com/";
int DNSTimeout = 1000;
int HTTPTimeout = 2000;

//Get the IP of the Host
URL url= null;
try {
     url = ResolveHostIP(sURL,DNSTimeout);
} catch (MalformedURLException e) {
    Log.d("INFO",e.getMessage());
}

if(url==null){
    //the DNS lookup timed out or failed.
}

//Build the request parameters
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTPTimeout);
HttpConnectionParams.setSoTimeout(params, HTTPTimeout);

DefaultHttpClient client = new DefaultHttpClient(params);

HttpResponse httpResponse;
String text;
try {
    //Execute the request (here it blocks the execution until finished or a timeout)
    httpResponse = client.execute(new HttpGet(url.toString()));
} catch (IOException e) {
    //If you hit this probably the connection timed out
    Log.d("INFO",e.getMessage());
}

//If you get here everything went OK so check response code, body or whatever
Run Code Online (Sandbox Code Playgroud)

使用方法:

//Run the DNS lookup manually to be able to time it out.
public static URL ResolveHostIP (String sURL, int timeout) throws MalformedURLException {
    URL url= new URL(sURL);
    //Resolve the host IP on a new thread
    DNSResolver dnsRes = new DNSResolver(url.getHost());
    Thread t = new Thread(dnsRes);
    t.start();
    //Join the thread for some time
    try {
        t.join(timeout);
    } catch (InterruptedException e) {
        Log.d("DEBUG", "DNS lookup interrupted");
        return null;
    }

    //get the IP of the host
    InetAddress inetAddr = dnsRes.get();
    if(inetAddr==null) {
        Log.d("DEBUG", "DNS timed out.");
        return null;
    }

    //rebuild the URL with the IP and return it
    Log.d("DEBUG", "DNS solved.");
    return new URL(url.getProtocol(),inetAddr.getHostAddress(),url.getPort(),url.getFile());
}   
Run Code Online (Sandbox Code Playgroud)

这个课程来自这篇博文.如果您将使用它,请查看备注.

public static class DNSResolver implements Runnable {
    private String domain;
    private InetAddress inetAddr;

    public DNSResolver(String domain) {
        this.domain = domain;
    }

    public void run() {
        try {
            InetAddress addr = InetAddress.getByName(domain);
            set(addr);
        } catch (UnknownHostException e) {
        }
    }

    public synchronized void set(InetAddress inetAddr) {
        this.inetAddr = inetAddr;
    }
    public synchronized InetAddress get() {
        return inetAddr;
    }
}
Run Code Online (Sandbox Code Playgroud)