2012-09-27 89 views
2

我有一个连接到服务器的应用程序。我设置了超时时间,将设备与互联网断开连接,并尝试执行发布请求以查看是否调用了超时,但连接一直持续不断。这是我的代码:Android:连接超时不工作(连接永远等待)

private static final int TIMEOUT_OPS = 3000 ; 
private HttpClient mHttpClient; 

public String sendToken(String token) throws IOException, AuthenticationException { 
    JSONArray jsonData = new JSONArray(); 
    jsonData.put(token); 

    final HttpPost post = prepareJSONRequest(jsonData.toString(), SEND_TOKEN_METHOD); 
    HttpClient httpClient = getConnection(); 
    Log.i(TAG, "Sending request"); 
    final HttpResponse resp; 
    try{ 
     resp = httpClient.execute(post); 
    }catch(Exception e){ 
     e.printStackTrace(); 
     return null; 
    } 
    Log.i(TAG, "Got response"); 
    ... 
} 

private HttpPost prepareJSONRequest(String rest_data, String method) throws AssertionError { 
    AbstractHttpEntity entity = null; 
    try { 
     final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair(KEY_PARAM_METHOD, method)); 
     params.add(new BasicNameValuePair(KEY_PARAM_INPUT_TYPE, JSON)); 
     params.add(new BasicNameValuePair(KEY_PARAM_RESPONSE_TYPE, JSON)); 
     params.add(new BasicNameValuePair("rest_data", rest_data)); 
     entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); 
     final HttpPost post = new HttpPost(mServer); 
     post.addHeader(entity.getContentType()); 
     post.setEntity(entity); 
     return post; 

    } catch (final UnsupportedEncodingException e) { 
     // this should never happen. 
     throw new AssertionError(e); 
    } 
} 

private HttpClient getConnection() { 
    if (mHttpClient == null) { 
     // registers schemes for both http and https 
     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 
     HttpProtocolParams.setUseExpectContinue(params, false); 
     HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_OPS); 
     HttpConnectionParams.setSoTimeout(params, TIMEOUT_OPS); 
     ConnManagerParams.setTimeout(params, TIMEOUT_OPS); 
     SchemeRegistry registry = new SchemeRegistry(); 
     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
     final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); 
     sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); 
     if (!mNoCertValidation) 
      registry.register(new Scheme("https", sslSocketFactory, 443)); 
     else 
      registry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); 
     ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); 
     mHttpClient = new DefaultHttpClient(manager, params); 

    } 
    return mHttpClient; 
} 

如果我执行此代码,我的日志显示“发送请求”,但不打印异常或“有回应”。为什么它不起作用?

+0

您是否在Manifest文件中设置了Internet的权限? – vandzi

+0

如果您没有Internet,则DNS请求将失败,但无法控制DNS超时。最终你应该得到一个UnknownHostException,但这可能需要几分钟的时间。在这种情况下,最好的做法是在发出HTTP请求的同时,在单独的线程中启动一个定时器。如果定时器在HTTP请求完成之前关闭,则可以中止HTTP请求。 –

+0

谢谢大卫,我会这样做。 –

回答

5

如果您没有Internet,则DNS请求将失败,但无法控制DNS超时。最终你应该得到一个UnknownHostException,但这可能需要几分钟的时间。在这种情况下,最好的做法是在发出HTTP请求的同时,在单独的线程中启动一个定时器。如果定时器在HTTP请求完成之前关闭,则可以中止HTTP请求。

+0

你的解释听起来很合理。人们可以做的另一件事是监听网络状态的变化,如http://stackoverflow.com/questions/3307237/how-can-i-monitor-the-network-connection-status-in-android中所述。 – wojciii

+1

@wojci true。但是,我的经验表明,如果您经常看到连接超时和DNS超时,但您没有看到网络状态事件更改(因为您在逻辑上具有连接性,则它不起作用)。对于用户启用/禁用连接的情况,网络状态更改很有用/可靠,或者您处于根本没有数据连接的情况。只是我个人的经验。 –

+0

这听起来很有道理,但是在使用'Thread'和'Thread.sleep(time)'尝试它并且使用'Timer.schedule()'调用'HttpGet.abort()'之后,在此方法之后没有'大约30秒后抛出IOException并执行execute()。 – AxeEffect