1. 程式人生 > >apache httpclient 獲取重定向之後的url方法

apache httpclient 獲取重定向之後的url方法

    public static void main(String[] args)
    {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        HttpGet httpGet = null;
        try
        {
            HttpContext httpContext = new BasicHttpContext();
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setSocketTimeout(10000).build();
            httpclient = HttpClients.createDefault();
            httpGet = new HttpGet(
                    "
http://www.baidu.com/link?url=PPyy80jv_4NXwwB211B8ksGsUMcdtm2iVkpXZ0wU0PQmoI5dFOR5IA0_Q7t6C4-9AlixI7r039abE4zmL73Z-a
");
            httpGet.setConfig(defaultRequestConfig);
            response = httpclient.execute(httpGet, httpContext);
            HttpHost currentHost = (HttpHost) httpContext
                    .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            HttpUriRequest req = (HttpUriRequest) httpContext
                    .getAttribute(ExecutionContext.HTTP_REQUEST);
            System.out.println((req.getURI().isAbsolute()) ? req.getURI()
                    .toString() : (currentHost.toURI() + req.getURI()));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }