Home > Mobile >  I Am Getting The 200 Status Code But Instead I Should get 302 Status Code, How Do I Solve It?
I Am Getting The 200 Status Code But Instead I Should get 302 Status Code, How Do I Solve It?

Time:02-02

I Was Making A Java Program That Can Check That We Will Redirect Or Not
There Are Some Status Codes In HTTPS, Like 200 Is For OK And 302 Is For Redirect,
So Heres My Code:

URL url = new URL("http://localhost/test/test_page_1.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
connection.getResponseCode();

The Line connection.getResponseCode(); Should Return 302 (Redirect Code) Because In The Php Code, header("location: pg_2.php") it sets location header to the page's location;
But Instead It Returns Me 200, I Am Using Xampp Wew Server, When I Open This Link In Browser, It Redirects Me, But Why I Am Not Getting 302 Code? Please Help Me,

EDIT: Also,
When I Used This Code:

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

Output:

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, 

There Is No Line Saying Location: pg2.php,
Why Its Happening, IDK
Please Help,
Thanks,

CodePudding user response:

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).

  • Related