java http请求超时抛出什么异常,Java http请求GET导致超时异常,但在浏览器中可以正常运行...

I have been playing with Http in Java and I faced a strange problem. Below is a piece code which executes GET method:

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();

}

So there are some sites (like the one provided in the Builder which cause:

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

What I do NOT understand is: why this works fine in the browser? I already set timeouts for 100seconds. I also tried with other HttpClients but with the same results (I believe deep down they use same classes anyways). Could anyone tell me where the problem lies, please?

Edit

I tried wget - worked, saved some HTML content.

curl returned: (52) Empty reply from server

解决方案

You have to use an User-Agent in your request. This works:

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();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值