安卓:连接超时不工作(连接永远等待) [英] Android: connection timeout not working (connection waits forever)

查看:252
本文介绍了安卓:连接超时不工作(连接永远等待)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到服务器上的应用程序。我设置了超时,从互联网上断开该设备并试图执行POST请求,看看是否超时被称为,但连接一直等待下去。这是我的code:

I have an application that connects to a server. I set a timeout, disconnected the device from internet and tried to execute the post request to see if the timeout was called, but the connection keeps waiting forever. This is my code:

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

如果我执行此code,我的日志显示正在发送请求,但是不打印异常或得到回应。为什么不工作?

If I execute this code, my log shows "Sending request", but doesn't print the exception or "Got response". Why doesn't it work?

推荐答案

如果你没有上网的DNS请求会失败,但你无法控制的DNS超时。最终,你应该得到一个UnknownHostException,但是这可能需要几分钟。在这种情况下,最好的办法是启动一个单独的线程的计时器在同一时间你做的HTTP请求。如果定时器熄灭HTTP请求已经完成之前,可以中止HTTP请求。​​

If you have no Internet the DNS request will fail, but you cannot control the DNS timeout. Eventually you should get an UnknownHostException, but this may take several minutes. In this case the best thing to do is to start a timer in a separate thread at the same time you make the HTTP request. If the timer goes off before the HTTP request has finished, you can abort the HTTP request.

这篇关于安卓:连接超时不工作(连接永远等待)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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