Following redirects in HTTPResponse Android

Deadly 提交于 2019-12-21 20:38:46

问题


I need to follow redirects given to me by HTTPost. When I make an HTTPost, and try to read the response, I get the redirect's page html. How can I fix this? Code:

public void parseDoc() {
    final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(params, true);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "https://secure.groupfusion.net/processlogin.php");
    String HTML = "";
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("referral_page",
                "/modules/gradebook/ui/gradebook.phtml?type=student_view"));
        nameValuePairs.add(new BasicNameValuePair("currDomain",
                "beardenhs.knoxschools.org"));
        nameValuePairs.add(new BasicNameValuePair("username", username
                .getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("password", password
                .getText().toString()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        String g = httppost.getURI().toString();

        HttpResponse response = httpclient.execute(httppost);

        HTML = EntityUtils.toString(response.getEntity());
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String ResponseBody = httpclient.execute(httppost, responseHandler);
        sting.setText(HTML);

    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

}

回答1:


When a server sends a redirect, it is actually sending a 3xx response code (usually 301 or 302) that indicates the redirect, and a Location header that tells you the new location.

So, in your case, you can get the Location header from the HttpResponse object and use that to send another request to retrieve the actual content after you've logged in. For example:

String newUrl = response.getFirstHeader("Location").getValue();

So long as you reuse the same HttpClient object for both requests, it should use any cookies set by the login request in your subsequent request(s).




回答2:


Try using the HttpGet method

GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).

For more info refer this

Hope it helps,

Cheers



来源:https://stackoverflow.com/questions/8462177/following-redirects-in-httpresponse-android

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