如何在Java中设置的Htt presponse超时为Android [英] How to set HttpResponse timeout for Android in Java

查看:120
本文介绍了如何在Java中设置的Htt presponse超时为Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了下面的函数用于检查连接状态:

I have created the following function for checking the connection status:

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

当我关闭服务器用于测试的执行等待很长的时间,行

When I shut down the server for testing the execution waits a long time at line

HttpResponse response = httpClient.execute(method);

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

Does anyone know how to set the timeout in order to avoid waiting too long?

谢谢!

推荐答案

在我的例如,两个超时设置。连接超时抛出java.net.SocketTimeoutException:套接字未连接和插座超时。java.net.SocketTimeoutException:操作超时

In my example two timeouts are set. The connection timeout throws "java.net.SocketTimeoutException: Socket is not connected" and the socket timeout "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()获取

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().

httpClient.setParams(httpParameters);

这篇关于如何在Java中设置的Htt presponse超时为Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆