我正在做一个Java程序,它可以检查我们是否会重定向
HTTPS中有一些状态代码,如200表示正常,302表示重定向,
所以这里我的代码:
URL url = new URL("http://localhost/test/test_page_1.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
connection.getResponseCode();
行connection.getResponseCode();
应该返回302(重定向代码),因为在Php代码中,header("location: pg_2.php") it sets location header to the page's location;
但相反,它返回我200,我正在使用Xampp Wew服务器,当我在浏览器中打开此链接,它重定向我,但为什么我没有得到302代码?请帮助我,
编辑:还有,
当我使用此代码:
URL url = new URL("http://localhost/hackTest/log.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.connect();
for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()){
System.out.print(entry.getKey() + ": ");
for (String str: entry.getValue()) {
System.out.print(str + ", ");
}
System.out.println();
}
输出:
Keep-Alive: timeout=5, max=100,
null: HTTP/1.1 200 OK,
Server: Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/8.1.4,
Connection: Keep-Alive,
Content-Length: 8,
Date: Wed, 01 Feb 2023 12:56:06 GMT,
Content-Type: text/html; charset=UTF-8,
X-Powered-By: PHP/8.1.4,
没有显示位置的行:pg2.php,
为什么会这样IDK
请救救我
谢谢你,
1条答案
按热度按时间xdnvmnnf1#
在Java代码中,调用
在你调用
connect()
之前。这意味着Java客户端...在接收到302响应时...将 * 执行重定向 *;也就是重新发送请求到重定向位置,当你调用getResponseCode()
或getHeaderFields()
时,你看到的是来自第二个(重定向的)GET的响应的细节。在本例中,重定向起作用,因此响应代码为200,并且头不包括
location
头。如果您想查看
302
响应及其头,请调用setInstanceFollowRedirects(false)
。