OKHttp handle 302
Asked Answered
A

2

7

Every time I perform a OKHttp Post request on this site, the response code is 302 and the response body is:

<html>
    <head>
        <title>Object moved</title>
    </head>
    <body>
        <h2>Object moved to <a href="/GradebookSummary.aspx">here</a>.
       </h2>
    </body>
</html>

Here is my code:

OkHttpClient client = new OkHttpClient().newBuilder()
                            .followRedirects(false)
                            .followSslRedirects(false)
                            .build();
                    MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                    RequestBody body = RequestBody.create(mediaType, "checkCookiesEnabled=true&checkMobileDevice=false&checkStandaloneMode=false&checkTabletDevice=false&portalAccountUsername=username&portalAccountPassword=password");
                    Request request = new Request.Builder()
                            .url("https://hac.chicousd.org/LoginParent.aspx?page=GradebookSummary.aspx")
                            .post(body)
                            .addHeader("content-type", "application/x-www-form-urlencoded")
                            .addHeader("cache-control", "no-cache")
                            .build();

                    Response response = client.newCall(request).execute();

My question is: How could I handle the response to be able to go to the new location?

Amberambergris answered 9/1, 2017 at 1:24 Comment(0)
A
1

All I needed to do was add a persistent cookie handler, which I found here.

Amberambergris answered 9/1, 2017 at 3:47 Comment(0)
S
7

OKhttp follows redirects by default but since you've explicitly disabled it in this case you'll need to check the Location header of the response to find the redirected url.

EDIT: You can get the new location via

String location = response.header('Location');
Sofar answered 9/1, 2017 at 1:41 Comment(6)
could you provide an exampleAmberambergris
Delete this: .followRedirects(false)Plourde
@JesseWilson I tried that, it gave me a page that said: you must enter a username and passwordAmberambergris
That means the page that you're trying to access requires authentication which is why you got redirected to the login page. Authenticate yourself first to access the pageSofar
I answered my own question, if you would like to edit your answer I will delete it and accept yoursAmberambergris
It would be better if you elaborate on your own answer and accept it. Could prove to be helpful for someone referring to it laterSofar
A
1

All I needed to do was add a persistent cookie handler, which I found here.

Amberambergris answered 9/1, 2017 at 3:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.