java:如果网络调用时间太长,抛出异常或错误?

时间:2010-12-16 08:48:06

标签: java

我开发了一种方法,可以发出网络http请求并等待响应。我现在想要处理一个场景,如果http响应需要比预期更长的时间,我想通过抛出某种异常加上错误来取消/终止该connectinn。

我不知道如何抛出异常和错误,我知道,我只是问我怎么能花多长时间来检索一个http响应呢?

psuedo下面是这样的:

  1. 启动一些计时器
  2. 制作http请求
  3. 等待http请求
  4. 如果在X之后没有检索到响应,则抛出错误/异常。
  5. 他们的情况是,当我确实发出一个http请求时,它需要一两分钟,然后jvm终于抛出一个异常但我希望更快地抛出这个异常而不是应用程序冻结并等待3-4分钟。

    提前致谢

    我正在为Android应用程序执行此操作,因此,对于如何实现此目的,Android特定的libs或java 5 libs应该是足够的。

    编辑:这是我的http请求代码如何使用apache libs:

        import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.entity.InputStreamEntity;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.protocol.BasicHttpContext;
    import org.apache.http.protocol.HttpContext;
    import org.apache.http.util.EntityUtils;
    
    
    private HttpClient httpclient;
    private HttpGet get;
    private HttpPost post;
    
    /**
         * POST request
         */
        private HttpResponseObject PostRequest() {
    
            //int response = 0;
    
            String responseBody = "";
            HttpResponseObject response = new HttpResponseObject();
    
            try {
    
                Log.d(TAG, "IN POST_REQUEST_METHOD");
                Log.d(TAG, "URL : " + url);
    
                httpclient = new DefaultHttpClient();
    
    
    
                post = new HttpPost(url);
    
    
                ByteArrayEntity entity = new ByteArrayEntity(data.getBytes());
                entity.setChunked(true);
    
                post.setEntity(new StringEntity(data));
    
                HttpResponse httpResponse = httpclient.execute(post);
    
                HttpEntity resEntity = httpResponse.getEntity();
    
    
                if (resEntity != null) {
                    // indicate that the content of this entity is no longer
                    // required
                    response.setResponseBody(EntityUtils.toString(resEntity));
    
                    Header[] header = httpResponse.getAllHeaders();
    
                    Log.d(TAG, "httpResponse.getAllHeaders() = " + header[0].getName());
                    response.setResponseHeader(httpResponse.getAllHeaders().toString());
                    resEntity.consumeContent();
                }
    
                // release all recources from the httpClient object
                httpclient.getConnectionManager().shutdown();
    
                response.setResponseCode(httpResponse.getStatusLine().getStatusCode() ) ;
    
                Log.d(TAG, "responseBody = " + response.getResponseBody());
                Log.d(TAG, "response code = " + response.getResponseCode());
                Log.d(TAG, "response header = " + response.getResponseHeader());
    
                return response;
    
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "exception e  = " + e.toString());
                return null;
            }
    
        }
    

3 个答案:

答案 0 :(得分:2)

您使用的是java.net.HttpUrlConnection吗? HttpUrlConnectionjava.net.UrlConnection的子类,其方法为setConnectTimeout(int)setReadTimeout(int)。一旦connect()InputStream.read()超过这些阈值,就会抛出IOException

查看Javadoc ...

setConnectTimeout

setReadTimeout

编辑: 啊,一些代码。我担心我不熟悉org.apache.http包,但看起来org.apache.http.client.methods.HttpGet继承自接口org.apache.http.client.methods.AbortableHttpRequest,所以你可以使用方法setConnectionRequest(ClientConnectionRequest connRequest)有一个方法getConnection (long timeout, TimeUnit tunit)。真的,我只是抓着吸管 - 如果你只是做一些基本的HTTP,我会说java.net.HttpUrlConnection

答案 1 :(得分:1)

假设您使用的是HttpClient 4.0.x,那么控制此类事情的方法是设置connection parameters

答案 2 :(得分:0)

您可以使用Future变量并使用Future.get(long timeout, TimeUnit unit)

  

...抛出某种异常加上错误

如果你在这里谈论的话,我建议你不要抛出Error

来自Error的文档:

  

错误是Throwable的子类,表示合理的应用程序不应该尝试捕获的严重问题