我创建了以下用于检查连接状态的功能:

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);


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

谢谢!

#1 楼

在我的示例中,设置了两个超时。连接超时引发java.net.SocketTimeoutException: Socket is not connected,套接字超时引发java.net.SocketTimeoutException: The operation timed out

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);


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

httpClient.setParams(httpParameters);


评论


@Thomas:我已经为您的用例解决方案编辑了答案

– kuester2000
2010-12-14在7:52

如果连接超时,HttpResponse将返回什么?在发出我的HTTP请求后,我随后在返回调用时检查状态代码,但是如果调用超时,则在检查此代码时会收到NullPointerException ...基本上,如何处理调用时的情况超时吗? (我使用的代码与您给出的答案非常相似)

– Tim
2011-2-27在16:45

@jellyfish-尽管有文档说明,AndroidHttpClient并未扩展DefaultHttpClient;而是实现了HttpClient。您将需要使用DefaultHttpClient来提供setParams(HttpParams)方法。

–特德·霍普(Ted Hopp)
2011-6-10 14:58

嗨,谢谢你的出色回答。但是,我想在连接超时时向用户敬酒...用什么方式我可以检测到连接超时?

– Arnab Chakraborty
2011-09-28 5:39

不起作用我在Sony和Moto上进行了测试,它们都被塞住了。

–thecr0w
13年7月8日在9:30



#2 楼

要在客户端上设置设置,请执行以下操作:

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


我已经在JellyBean上成功使用了此设置,但也可以在较旧的平台上使用....

HTH

评论


与HttpClient有什么关系?

– Sazzad Hissain Khan
19 Mar 19 '19在15:08

#3 楼

如果您使用的是雅加达的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);


评论


HttpClientParams.CONNECTION_MANAGER_TIMEOUT未知

– Tawani
2010-2-1 15:22

您应该对* _TIMEOUT参数使用client.getParams()。setIntParameter(..)

– loafoe
2011年5月9日13:07

怎么找?设备已连接到wifi,但实际上未通过wifi获取活动数据。

–甘尼什·卡蒂卡(Ganesh Katikar)
14年8月14日在13:02

#4 楼

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

com / 2009/03/17 / configure-timeout-with-apache-httpclient-40 /

#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 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());
}   


此类来自此博客文章。去检查是否要使用它。

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;
    }
}


#6 楼

一种选择是使用来自Square的OkHttp客户端。

添加库依赖项

在build.gradle中,包括以下行:

compile 'com.squareup.okhttp:okhttp:x.x.x'


其中x.x.x是所需的库版本。

设置客户端

例如,如果要将超时设置为60秒,请这样做:

final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);



ps:如果minSdkVersion大于8,则可以使用TimeUnit.MINUTES。因此,您可以简单地使用:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);


有关单位的更多详细信息,请参见TimeUnit。

评论


在当前版本的OkHttp中,需要对超时进行不同的设置:https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java

– thijsonline
17年11月29日在9:09



#7 楼

HttpParams httpParameters = new BasicHttpParams();
            HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParameters,
                    HTTP.DEFAULT_CONTENT_CHARSET);
            HttpProtocolParams.setUseExpectContinue(httpParameters, true);

            // Set the timeout in milliseconds until a connection is
            // established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = 35 * 1000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 30 * 1000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);


评论


不完整。与HttpClient有什么关系?

– Sazzad Hissain Khan
19年3月19日在15:09

#8 楼

您可以使用Httpclient-android-4.3.5的方式创建HttpClient实例,它可以很好地工作。

#9 楼

如果您使用的是HttpURLConnection,请按此处所述致电setConnectTimeout()

URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);


评论


该描述更像是建立连接的超时,而不是http请求?

–user2499800
19年4月24日在4:45

#10 楼

public boolean isInternetWorking(){
    try {
        int timeOut = 5000;
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53);
        socket.connect(socketAddress,timeOut);
        socket.close();
        return true;
    } catch (IOException e) {
        //silent
    }
    return false;
}


评论


它代表哪个服务器? “ 8.8.8.8”,53

–朱纳德
19/12/22在20:18