HttpURLConnection getInputStream() has one second

2019-06-07 21:02发布

问题:

I am using HttpURLConnection for making POST requests. I observe always the same behaviour during tests:

  1. first request runs very fast (miliseconds)
  2. all following requests take one second + some miliseconds

So something is causing 1 second delay. What can it be? The delay is happening exactly in HttpURLConnection#getInputStream(). I replaced the implementation with HttpClient - then everything is OK, no second delays (so it is not the server fault). But I really don't want to use any external dependency, so I would like to fix the HttpURLConnection thing... Any ideas?

Below current implementation. I tried some tips from stackoverflow (adding headers to the request), but with no success.

        URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");

    con.setRequestProperty("Content-Length", ""
        + (body == null ? 0 : body.length));

    // Send post request
    con.setDoOutput(true);
    OutputStream wr = con.getOutputStream();
    if (body != null) {
    wr.write(body);
    }
    wr.flush();
    wr.close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(
        con.getInputStream()));
    String line;
    String result = "";
    while ((line = rd.readLine()) != null) {
    result += line;
    }

    rd.close();
    con.disconnect();

    return result;

PS: It is about jse, not android.

回答1:

You're never closing the input stream from the connection - that may mean that the connection isn't eligible for pooling, and on the next attempt it's waiting for up to a second to see if the previous request's connection will become eligible for pooling.

At the very least, it would be a good idea to close the stream. Use a try-with-resources block if you're using Java 7 - and ditto for the writer.

As an aside, I suggest you explicitly state the encoding you expect when reading - or use a higher-level library which detects that automatically based on headers.