以下代码让我疯狂。它有时会返回错误的响应代码,我不明白为什么。例如,http://www.ebay.com/itm/131709867498
在现实生活中返回301 Moved Permanently
(Chrome和Edge),而以下代码返回200
。非常感谢提前。 (如果重要,我正在运行Java 1.8.0_66。)
HttpURLConnection connection = (HttpURLConnection)new URL("http://www.ebay.com/itm/131709867498").openConnection();
connection.setRequestMethod("HEAD");
connection.setInstanceFollowRedirects(false);
int statusCode = connection.getResponseCode();
System.out.println(statusCode);
答案 0 :(得分:1)
当我在Curl中运行您的网址时,我得到一个'200'。为什么你认为它应该返回301?
url -I "http://www.ebay.com/itm/131709867498"
HTTP/1.1 200 OK
X-EBAY-C-REQUEST-ID: ri=yGq%2BS7ChLgXP,rci=XOZjR%2BAfGDb5BkY5
RlogId: t6ulcpjqcj9%3Feog4d71f%2B66%600-15436278e5c-0x17a
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Type: text/html;charset=UTF-8
Content-Language: en-US
Content-Length: 0
Server: Server
Date: Thu, 21 Apr 2016 00:10:42 GMT
Connection: keep-alive
Set-Cookie: JSESSIONID=4694AD028535546045A4E2853D7F8B72; Path=/; HttpOnly
Set-Cookie: ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/
Set-Cookie: dp1=bu1p/QEBfX0BAX19AQA**58f94e02^bl/US5ada8182^;Domain=.ebay.com;Expires=Sat, 21-Apr-2018 00:10:42 GMT;Path=/
Set-Cookie: s=CgAD4ACBXGWwCMzYyNzhlNTcxNTQwYTYyMjg3MDFkNTExZmZiN2MyMGKrI6lP;Domain=.ebay.com;Path=/; HttpOnly
Set-Cookie: nonsession=CgADLAAFXGCGKMQDKACBgfhwCMzYyNzhlNTcxNTQwYTYyMjg3MDFkNTExZmZiN2MyMGIcCAX2;Domain=.ebay.com;Expires=Fri, 21-Apr-2017 00:10:42 GMT;Path=/
答案 1 :(得分:1)
您正在使用“Head”方法,但浏览器使用“GET”方法,如果您更改
connection.setRequestMethod("HEAD");
要
connection.setRequestMethod("GET");
您将看到301状态代码