在HTTPResponse Android中重定向之后 [英] Following redirects in HTTPResponse Android

查看:241
本文介绍了在HTTPResponse Android中重定向之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遵循HTTPost给我的重定向。当我创建一个HTTPost,并尝试读取响应时,我得到重定向的页面html。我怎样才能解决这个问题?代码:

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) {
    }

}


推荐答案

当服务器发送重定向时,它实际上是发送3xx响应代码(通常为301或302)表示重定向,以及一个告诉您新位置的Location标头。

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.

因此,在您的情况下,您可以从HttpResponse 对象并使用它发送另一个请求来检索实际登录后的内容。例如:

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

只要为两个请求重复使用相同的HttpClient对象,它就应该使用由后续请求中的登录请求。

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).

这篇关于在HTTPResponse Android中重定向之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆