代理访问网页,拿到图片,文件最终指向地址

网页中会用到很多相对路径 ../等

 1 if (url.startsWith("../")) {
 2             String link = getRealLink(hostUrl.getPath());
 3             String[] str = hostUrl.getPath().split("/");
 4             int len = url.split("\\.\\./").length;
 5             String s = "";
 6             if (link.split("/").length != 3) {
 7                 for (int i = 0; i < str.length - len; i++) {
 8                     s += str[i] + "/";
 9                 }
10                 url = s + url.replaceAll("\\.\\./", "");
11             } else {
12                 url = link + "/" + url.replaceAll("\\.\\./", "");
13             }
14         }
 1 /**
 2      * 获得最终访问地址
 3      * 
 4      * @param link
 5      * @return
 6      * @throws ProtocolException
 7      */
 8     private String getRealLink(String link) {
 9         DefaultHttpClient httpClient = new DefaultHttpClient();
10         HttpGet httpget = new HttpGet(link);
11         HttpContext context = new BasicHttpContext();
12         HttpResponse response = null;
13         try {
14             response = httpClient.execute(httpget, context);
15         } catch (ClientProtocolException e1) {
16         } catch (IOException e1) {
17         }
18         if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
19             try {
20                 throw new IOException(response.getStatusLine().toString());
21             } catch (IOException e) {
22             }
23         HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
24         HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
25         link = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq
26                 .getURI());
27         return link;
28     }

简单记录下!

来自:http://stackoverflow.com/questions/1456987/httpclient-4-how-to-capture-last-redirect-url

posted @ 2012-12-14 15:25  悟寰轩-叶秋  阅读(487)  评论(0编辑  收藏  举报