Following redirects in HTTPResponse Android

2020-07-22 19:13发布

问题:

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