Sometimes HttpURLConnection.getInputStream executes too slowly

前端 未结 6 1285
情深已故
情深已故 2020-12-09 12:56

We have next code.
Sometimes we should wait 10-20-40 seconds on the last line.
What can be the problem?

Java 1.4

URL url = ...;
HttpURLConn         


        
相关标签:
6条回答
  • 2020-12-09 13:06

    The problem can be something from network sub layer... Should be hard to find it.

    But what about the setReadTimeOut() with low value and a while loop?

    0 讨论(0)
  • 2020-12-09 13:06

    One thing I would guess is that your DNS server isn't responding well.

    Can you experiment with changing symbolic domain names to numeric IP addresses before you start? Or can you do each request twice (just for experimentation) and see if the first request is significantly slower than the second?

    Google has put up a DNS server at (among others) 8.8.8.8 . They claim it's faster than most other DNS servers. Give that a try!

    0 讨论(0)
  • 2020-12-09 13:12

    Try it with an IP address. To see if it's a DNS problem.

    0 讨论(0)
  • 2020-12-09 13:14

    Had the same problem, found out it was caused by IPv6.

    You Disable it from code using:

    System.setProperty("java.net.preferIPv4Stack" , "true");
    

    You can also disable it via the command line using : g-Djava.net.preferIPv4Stack=true

    0 讨论(0)
  • 2020-12-09 13:16

    'We had a similar issue which is caused by buggy keep-alive in old Java. Add this before connect to see if it helps,

    conn.setRequestProperty("Connection", "close");
    

    or

    System.setProperty("http.keepAlive", "false");
    
    0 讨论(0)
  • 2020-12-09 13:27

    I had same problem, so i change to HTTPClient from Apache, follow a example:

    HttpClient httpClient = HttpClientBuilder.create().build();
    
    HttpPost request = new HttpPost("www.myurl-to-read");
    
    RequestConfig requestConfig = RequestConfig.custom()
                                  .setSocketTimeout(8000)
                                  .setConnectTimeout(10000)
                                  .setConnectionRequestTimeout(1000)
                                  .build();
    
    request.setConfig(requestConfig);
    
    request.setHeader("Content-type", "application/json");
    
    HttpResponse  response = httpClient.execute(request);
    
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity, "UTF-8");
    
    0 讨论(0)
提交回复
热议问题