2

我正在尝试连接到必须获取数据的互联网,如果连接时间超过 5 秒,我必须完成该过程并继续离线工作。
一切正常,有时return互联网不可用大约需要 10 秒,现在我必须xml == null;在时间超过时间限制时返回,
我不想在异步任务中执行此操作

    public String getUrlData(String url) {
    String xml = null;

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    System.out.println("waiting");
    HttpResponse httpResponse;

    try {
        // start the timer here

        httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

        // check if the timer has exceeded by "if else"
        // move to "return xml;" Manually when exceeds 5sec, but how?

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return xml;

}

此答案后编辑的代码

public String getUrlData(String url) {
    String xml = null;

    final int TIMEOUT_MILLISEC = 5000; // 5 seconds

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);
    System.out.println("waiting");
    HttpResponse httpResponse;

    try {
        // start the timer here
        System.out.println("Started");
        httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Ended");
    return xml;

}

LogCat 在这里 >> 20 秒

4

5 回答 5

8

您需要做的就是为您的连接定义一个超时限制。例如:

final int TIMEOUT_MILLISEC = 5000;  // 5 seconds

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpClient httpClient = new DefaultHttpClient(httpParams);

然后,httpClient以与使用它相同的方式使用它。


编辑

public String getUrlData(String url) {
String xml = null;

final int TIMEOUT_MILLISEC = 5000;  // 5 seconds

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;

try {
    // start the timer here

    httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    xml = EntityUtils.toString(httpEntity);

    // check if the timer has exceeded by "if else"
    // move to "return xml;" Manually when exceeds 5sec, but how?

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return xml;

}
于 2012-09-10T08:10:16.460 回答
2

这个怎么样:

Thread thread = new Thread() {
  @Override
  public void run() {
    // do the downloading thing..
  }
};
thread.start();
thread.join(5000);
于 2012-09-10T08:10:43.180 回答
1

这只是一个想法,但您可以设置一个延迟的可运行文件,并在 5 秒后检查文件是否有任何大小。

于 2012-09-10T08:09:24.710 回答
0
 HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",
            PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https",
            SSLCertificateSocketFactory.getHttpSocketFactory(
            SOCKET_OPERATION_TIMEOUT, sessionCache), 443));

    ClientConnectionManager manager =
            new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);

根据您的需要更改 SOCKET_OPERATION_TIMEOUT 值。

于 2012-09-10T08:11:19.073 回答
0

此代码可以帮助您

上一个答案中的这段代码是好的

final int TIMEOUT_MILLISEC = 5000;  // 5 seconds

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpClient httpClient = new DefaultHttpClient(httpParams);

只有当您尝试执行您的请求时,您才需要关心另外 3 个异常 SocketTimeoutException、UnknownHostException、ConnectTimeoutException

所以也要抓住这 3 个例外。

于 2012-09-12T13:51:34.233 回答