如何通过HttpURLConnection得到http 302的跳转地址

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

如果不想直接跳转到目标地址,想对中间的Location做些处理则可以通过HttpURLConnection实现。 // 必须设置false,否则会自动redirect到Location的地址 conn.setInstanceFollowRedirects(false);

package com.zuidaima;import java.net.HttpURLConnection;import java.net.URL;/** * 如何通过HttpURLConnection得到http 302的跳转地址 *  * @author javaniu *  */public class Http302 public static void main(String[] args) {  try {   String url = "http://www.zuidaima.com/302.htm";   System.out.println("访问地址:" + url);   URL serverUrl = new URL(url);   HttpURLConnection conn = (HttpURLConnection) serverUrl     .openConnection();   conn.setRequestMethod("GET");   // 必须设置false,否则会自动redirect到Location的地址   conn.setInstanceFollowRedirects(false);   conn.addRequestProperty("Accept-Charset", "UTF-8;");   conn.addRequestProperty("User-Agent",     "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");   conn.addRequestProperty("Referer", "http://zuidaima.com/");   conn.connect();   String location = conn.getHeaderField("Location");   serverUrl = new URL(location);   conn = (HttpURLConnection) serverUrl.openConnection();   conn.setRequestMethod("GET");   conn.addRequestProperty("Accept-Charset", "UTF-8;");   conn.addRequestProperty("User-Agent",     "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");   conn.addRequestProperty("Referer", "http://zuidaima.com/");   conn.connect();   System.out.println("跳转地址:" + location);  } catch (Exception e) {   e.printStackTrace();  } }}        

转载: http://www.zuidaima.com/share/1550463509482496.htm

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

你可能感兴趣的:(如何通过HttpURLConnection得到http 302的跳转地址)