HttpClient取得自定义的状态码302,并获取Header中的参数Location

1.导入如下两个包:

  

         下载地址:https://files.cnblogs.com/files/zhougaojun/httpclient_lib.zip

 2.接收Google返回的302状态码,并获得Location参数,如下是代码关键部分

      DefaultHttpClient httpclient = new DefaultHttpClient();
       String location = null;
       int responseCode = 0;
       try {
           final HttpGet request = new HttpGet(googleUrl);  
           org.apache.http.params.HttpParams params = new BasicHttpParams();
           params.setParameter("http.protocol.handle-redirects", false); // 默认不让重定向
           request.setParams(params);
           HttpResponse response = httpclient.execute(request);
           responseCode = response.getStatusLine().getStatusCode();
           System.out.println(responseCode);
          if(responseCode==200){
             LOG.info(MessageFormat.format("[{0}]|[成功200]|[url:{1}]|[status:{2}]",tag,googleUrl,responseCode));
          }else if(responseCode==302){
             org.apache.http.Header locationHeader = response.getFirstHeader("Location");
             if(locationHeader!=null){
                    location = locationHeader.getValue();
                    LOG.info(MessageFormat.format("[{0}]|[成功{1}]|[url:{2}]|[status:{3}]|[{location:{4}}]",tag,responseCode,googleUrl,responseCode,location));
             }
          }
       } catch (Exception e) {
           e.printStackTrace();
           LOG.error(MessageFormat.format("[{0}]|[异常]|[url:{1}]|[status:{2}]|[content:{3}]]",tag,googleUrl,responseCode,e.getMessage()));
       }

 

 3.Googleservice 302返回

posted @ 2015-06-02 18:42  telzhou  阅读(16431)  评论(1编辑  收藏  举报