I made a Java program to check whether a web request will redirect or not.
As there are some status codes in HTTP protocol, I need to look for 302 status code that expresses redirect request,
Here is my code spinnet:
URL url = new URL("http://localhost/test/test_page_1.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
var code = connection.getResponseCode();
The code
variable shall contain the 302 value as my PHP code sets a 302 redirect code and location header by the following code header("location: pg_2.php")
, but instead, It contains 200 code expressing OK.
I have checked using Wireshark, It returns 302.
What can be the potential issue causing this?
In your Java code, you are calling
connection.setInstanceFollowRedirects(true);
before you make the connect()
call. That means that the Java client ... on receiving a 302 response ... will perform the redirect; i.e. resend the request to the redirect location. What you see when you call getResponseCode()
or getHeaderFields()
are the the details of the response from the 2nd (redirected) GET.
In this case the redirect works, so the response code is 200 and the headers don't include the location
header.
If you want to see the 302
response and its headers, call setInstanceFollowRedirects(false)
.