Java http请求GET导致超时异常,而它在浏览器中工作正常

时间:2017-12-05 14:23:46

标签: java http https socket-timeout-exception okhttp

我一直在HttpJava我遇到了一个奇怪的问题。下面是执行GET方法的片段代码:

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(100, TimeUnit.SECONDS);
client.setReadTimeout(100, TimeUnit.SECONDS);
Response response = null;
Request request = new Request.Builder()
        .url("https://www.celebritycruises.com/")
        .get()
        .build();
try {
    response = client.newCall(request).execute();
    System.out.println(response.code());
} catch (IOException e) {
    e.printStackTrace();
} 

因此,有一些网站(例如Builder中提供的网站导致:

java.net.SocketTimeoutException: timeout
at okio.Okio$3.newTimeoutException(Okio.java:207)
at okio.AsyncTimeout.exit(AsyncTimeout.java:261)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:215)
[...]
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:940)

at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at okio.Okio$2.read(Okio.java:139)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
... 38 more

我不明白的是:为什么这在浏览器中运行良好?我已为timeouts设置了100seconds。我也试过其他HttpClients,但结果相同(我相信他们在内心深处都使用相同的类)。谁能告诉我问题在哪里,拜托?

修改

我试过wget - 工作,保存了一些HTML内容。 curl已退回:(52) Empty reply from server

1 个答案:

答案 0 :(得分:2)

您必须在请求中使用User-Agent。这有效:

Request request = new Request.Builder().url("https://www.celebritycruises.com/").header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0").build();