Xutils-http-HttpClient get请求在HttpResponse中无法获得Location的问题

我通过httpclient的get方法访问,

通过返回的response的头部的location可以得到服务器的重定向地址(Location)
在java环境下测试都没问题
 
可是在安卓SDK环境下 却得不到response的location
通过抓包分析,发现在android下,
httpclient的实例执行get请求后,一起连重定向的get方法都执行了 
所以最后得到的response是重定向之后地址的get请求的response,所以得不到locatioon,而且responseCode==200,而不是在java测试环境下的302,说明这个时候的response是重定向之后的response
这个时候需要阻止HttpClient的自动重定向,方法如下:
 
 
 
public static String  getLocationMethod(String reqUrl, Context context) {
         DefaultHttpClient httpclient = new DefaultHttpClient();
        String location = null;
        int responseCode = 0;
        try {
            final HttpGet request = new HttpGet(reqUrl);
            HttpParams params = new BasicHttpParams();
            params.setParameter("http.protocol.handle-redirects", false); // 默认不让重定向
                                                                            // 这样就能拿到Location头了
            request.setParams(params);
            HttpResponse response = httpclient.execute(request);
            responseCode = response.getStatusLine().getStatusCode();
            Header[] headers = response.getAllHeaders();
 
           if(responseCode==302){
              Header locationHeader = response.getFirstHeader("Location");
             if (locationHeader != null) {
                location = locationHeader.getValue();
              }
 
          }
        } catch (Exception e) {
            e.printStackTrace();
            MyLog.d("exception=", e.toString());
        }
        return location;
    }
 
添加  params.setParameter("http.protocol.handle-redirects", false);之后返回结果如下:
ResponseCode=    302
Date:Sun, 04 Jan 1970 18:38:36 GMT
Server:Abloomy Http Server 1.0
Connection:Close
Cache-Control:no-store
Pragma:no-caches
Last-Modified:Sun, 04 Jan 1970 18:38:36 GMT
Content-Typ:text/html; charset=iso-8859-1
Content-Length:1016
Expires:Mon, 01 Jan 1980 08:00:00 GM
Location:http://124.205.91.166/i8n/index.php?wlanacip=124.205.91.166&wlanacname=124.205.91.180&wlanuserip=224.48.0.1&vslanusermac=f05a0965503c&vslanessid=ABLOOMY-WK
原文地址:https://www.cnblogs.com/weixiao870428/p/3793296.html