方法1:
/** * 获取重定向地址 * @param path 原地址 * @return * @throws Exception */ private String getRedirectUrl(String path) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(path) .openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(5000); return conn.getHeaderField("Location"); } }
方法2:
/** * 处理跳转链接,获取重定向地址 * @param url 源地址 * @return 目标网页的绝对地址 */ public String getAbsUrl(String url){ CloseableHttpClient httpclient = HttpClients.createDefault(); HttpClientContext context = HttpClientContext.create(); HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = null; String absUrl = null; try { response = httpclient.execute(httpget, context); HttpHost target = context.getTargetHost(); List<URI> redirectLocations = context.getRedirectLocations(); URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations); System.out.println("Final HTTP location: " + location.toASCIIString()); absUrl = location.toASCIIString(); }catch(IOException e){ e.printStackTrace(); }catch (URISyntaxException e) { e.printStackTrace(); }finally { try { httpclient.close(); response.close(); } catch (IOException e) { e.printStackTrace(); } } return absUrl; }
标签:return,重定向,URL,location,context,Java,conn,String From: https://www.cnblogs.com/privateLogs/p/17563652.html