java+HttpClient获取百度搜索结果重定向后的地址

百度搜索结果那长条真是恶心,来个获取百度301||302重定向后的真实地址。

 

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;


public class Redirect {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
        
        //使用Get方式请求
        HttpGet httpget = new HttpGet("http://www.baidu.com/link?url=ByBJLpHsj5nXx6DESXbmMjIrU5W4Eh0yg5wCQpe3kCQMlJK_RJBmdEYGm0DDTCoTDGaz7rH80gxjvtvoqJuYxK");
        HttpParams params = client.getParams();  
        params.setParameter(AllClientPNames.HANDLE_REDIRECTS, false);
           
        //执行请求
        try {
            HttpResponse response = client.execute(httpget);
            int statusCode=response.getStatusLine().getStatusCode();
            if(statusCode==301||statusCode==302)
            {
                Header[] hs = response.getHeaders("Location");
			     for(Header h:hs)
			     {
			    	 System.out.println(h.getName()+"--"+h.getValue());
			     }
            }
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
	}

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注