获取IP地址 & 伪装IP地址发送请求
//获取请求客户端IP地址
public final static String getIpAddress(HttpServletRequest request) throws IOException {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
//指定伪IP地址代理请求
String visitIP=getIpAddress(request);
URL url = new URL("http://www.baidu.com");
URLConnection connection = url.openConnection();
connection.setRequestProperty("X-Forwarded-For",visitIP);
connection.setRequestProperty("Proxy-Client-IP",visitIP);
connection.setRequestProperty("WL-Proxy-Client-IP",visitIP);
connection.setRequestProperty("HTTP_CLIENT_IP",visitIP);
connection.setRequestProperty("HTTP_X_FORWARDED_FOR",visitIP);
connection.setRequestProperty("REMOTE_ADDR",visitIP);
connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19");
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(30000);
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line;
while((line = reader.readLine())!= null){
result.append(line);
}
System.out.prinlt(result.toString());