HttpURLConnection unable to capture HTTP 302 correctly in a Java test

67 views Asked by At

I am trying to write a test for a URL /rdrct which redirects to another URL, say /test on the same host. On the application, the redirect works fine and I see a HTTP 302 in the Network Inspector but when I write a Java test, it fails and I get the following error.

expected: <200> but was: <302>

@Test
public void testRedirect() throws Exception { 
    String uri = "http://localhost:" + port + "/rdrct";
    URL url = new URL(uri);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(true);
    connection.setRequestProperty("Accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,"
        + "image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
    connection.connect();
    int responseCode = connection.getResponseCode();
    assertEquals(responseCode, 302); 
}

What am I missing or doing wrong?

0

There are 0 answers