开发者

java: throw exception or error if a network call takes too long?

i have developed a method that makes a network http request and waits for the response. i now want to handle a scenario where if the http response takes longer then expected, i want to cancel/terminate that connectinn by throwing some kind of exception plus an error.

im not asking how to throw exceptions and errors, i know that, im just asking how i can some how time how long its taking for me to retrieve a http response?

psuedo below is something like this:

  1. start some timer
  2. make http request
  3. wait for http request
  4. if response doesnt get retrieved after X, throw error/exception.

Their has been cases where when i do make a http request it takes a minute or two before the jvm finally throws an exception but i wish to throw this exception quicker instead of the app freezing and waiting 3-4mins.

Thanks in advance

Im doing this for a android application so either android specific libs or java 5 libs should be sufficiant for an example on how to achieve this.

edit: here is how my http request code looks like using 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(http开发者_C百科Response.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;
        }

    }


Are you using java.net.HttpUrlConnection? HttpUrlConnection is a subclass of java.net.UrlConnection, which has methods setConnectTimeout(int) and setReadTimeout(int). Once these thresholds are exceeded on either connect() or InputStream.read(), then an IOException will be thrown.

Check out the Javadoc at...

setConnectTimeout

and

setReadTimeout

EDIT: Ah, some code. I'm afraid I'm not that familiar with the org.apache.http package, but it looks like org.apache.http.client.methods.HttpGet inherits from the interface org.apache.http.client.methods.AbortableHttpRequest, so you could use the method setConnectionRequest(ClientConnectionRequest connRequest) which has a method getConnection (long timeout, TimeUnit tunit). Really, I'm just clutching at straws here - If you're only doing something basic with HTTP, I'd say go for java.net.HttpUrlConnection.


Assuming that you are using HttpClient 4.0.x, then the way to control this kind of thing is by setting connection parameters.


You could use a Future variable and use the Future.get(long timeout, TimeUnit unit).

... throwing some kind of exception plus an error

I would like to advice you not to throw an Error if that's what you're talking about here.

From the documentation of Error:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜