OKHttp handle 302

和自甴很熟 提交于 2019-12-12 21:23:06

问题


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?


回答1:


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');



回答2:


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



来源:https://stackoverflow.com/questions/41539750/okhttp-handle-302

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!