前言:很久之前有过多次这样的场景,A机器访问C机器访问不了,而A机器可以访问B机器,B机器也可以访问C机器,所以就可以使用B做代理机,实现A访问B从而实现A访问C。
在B机器搭建nginx服务并实现代理
安装略过,这里贴一下配置文件设置
server {
listen 80;
location / {
resolver 114.114.114.114;#DNS 地址
proxy_pass http://$host$request_uri;
}
java代码请求实现(url代理实现方式有两种)
方式一:使用该方式后,所有的请求都将使用代理服务器访问
// 对http开启全局代理
System.setProperty("http.proxyHost", "192.168.3.26");
System.setProperty("http.proxyPort", "80");
// 对https开启全局代理
System.setProperty("https.proxyHost", "192.168.3.26");
System.setProperty("https.proxyPort", "80");
//目标访问url地址
URL url = new URL("http://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
方式二:可以实现谁调用谁代理发送
// 代理访问http请求
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.3.26", 80));
//目标访问url地址
URL url = new URL("http://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
编写java代理工具
package com.lhkj.iot.controller;
import java.io.*;
import java.net.*;
/**
* @author mage
*/
public class HttpProxyUtils {
public static void main(String[] args) {
String ss = doGetNoParameters("http://www.baidu.com");
System.out.println(ss);
}
/**
* http get请求, 不带参数
* @param requestURL
* @return
*/
public static String doGetNoParameters(String requestURL) {
// 对http开启全局代理
System.setProperty("http.proxyHost", "192.168.3.26");
System.setProperty("http.proxyPort", "80");
// 对https开启全局代理
System.setProperty("https.proxyHost", "192.168.1.1");
System.setProperty("https.proxyPort", "80");
// 记录信息
StringBuffer buffer = new StringBuffer();
HttpURLConnection conn = null;
try {
URL url = new URL(requestURL);
// 判断是否需要代理模式请求http
// if (proxyHost != null && proxyPort != null) {
// // 如果是本机自己测试, 不需要代理请求,但发到服务器上的时候需要代理请求
// // 对http开启全局代理
// //System.setProperty("http.proxyHost", proxyHost);
// //System.setProperty("http.proxyPort", proxyPort);
// // 对https开启全局代理
// //System.setProperty("https.proxyHost", proxyHost);
// //System.setProperty("https.proxyPort", proxyPort);
//
// // 代理访问http请求
// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
// conn = (HttpURLConnection) url.openConnection(proxy);
// } else {
// 原生访问http请求,未代理请求
conn = (HttpURLConnection) url.openConnection();
// }
// 设置请求的属性
conn.setDoOutput(true); // 是否可以输出
conn.setRequestMethod("GET"); // 请求方式, 只包含"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"六种
conn.setConnectTimeout(60000); // 最高超时时间
conn.setReadTimeout(60000); // 最高读取时间
conn.setConnectTimeout(60000); // 最高连接时间
// 读取数据
InputStream is = null;
InputStreamReader inputReader = null;
BufferedReader reader = null;
try {
is = conn.getInputStream();
inputReader = new InputStreamReader(is, "UTF-8");
reader = new BufferedReader(inputReader);
String temp;
while ((temp = reader.readLine()) != null) {
buffer.append(temp);
}
} catch (Exception e) {
System.out.println("HttpGetUtils doGetNoParameters error: " + e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (inputReader != null) {
inputReader.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
System.out.println("HttpGetUtils doGetNoParameters error: " + e);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 当http连接空闲时, 释放资源
if (conn != null) {
conn.disconnect();
}
}
// 返回信息
return buffer.length()==0 ? "" : buffer.toString();
}
/**
* post请求
* @param requestURL
* @param params
* @param proxyHost
* @param proxyPort
* @return
*/
public static String doPost(String requestURL, String params, String proxyHost, Integer proxyPort) {
// 记录信息
StringBuffer buffer = new StringBuffer();
HttpURLConnection conn = null;
try {
URL url = new URL(requestURL);
// 判断是否需要代理模式请求http
if (proxyHost != null && proxyPort != null) {
// 如果是本机自己测试, 不需要代理请求,但发到服务器上的时候需要代理请求
// 对http开启全局代理
//System.setProperty("http.proxyHost", proxyHost);
//System.setProperty("http.proxyPort", proxyPort);
// 对https开启全局代理
//System.setProperty("https.proxyHost", proxyHost);
//System.setProperty("https.proxyPort", proxyPort);
// 代理访问http请求
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) url.openConnection(proxy);
} else {
// 原生访问http请求,未代理请求
conn = (HttpURLConnection) url.openConnection();
}
// 设置请求的属性
// 是否可以输出
conn.setDoOutput(true);
// 请求方式, 只包含"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"六种
conn.setRequestMethod("POST");
// 最高超时时间
conn.setConnectTimeout(60000);
// 最高读取时间
conn.setReadTimeout(60000);
// 最高连接时间
conn.setConnectTimeout(60000);
// 是否可以输入
conn.setDoInput(true);
if (params != null) {
// 设置参数为json格式
conn.setRequestProperty("Content-type", "application/json");
// 写入参数信息
OutputStream os = conn.getOutputStream();
try {
os.write(params.getBytes("UTF-8"));
} catch (Exception e) {
System.out.println("HttpPostUtils doPost error: " + e);
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
System.out.println("HttpPostUtils doPost error: " + e);
}
}
}
// 读取数据
InputStream is = null;
InputStreamReader inputReader = null;
BufferedReader reader = null;
try {
is = conn.getInputStream();
inputReader = new InputStreamReader(is, "UTF-8");
reader = new BufferedReader(inputReader);
String temp;
while ((temp = reader.readLine()) != null) {
buffer.append(temp);
}
} catch (Exception e) {
System.out.println("HttpPostUtils doPost error: " + e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (inputReader != null) {
inputReader.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
System.out.println("HttpPostUtils doPost error: " + e);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 当http连接空闲时, 释放资源
if (conn != null) {
conn.disconnect();
}
}
// 返回信息
return buffer.length()==0 ? "" : buffer.toString();
}
}
带有验证条件的代理
如果你的代理服务器不需要验证,那到此就结束了。下面有验证的,这时就需要java.net.Authenticator类来完成一般的Http验证。但是java.net.Authenticator这个类却是个抽象类,我们要使用还需要实例化一下子自己的类。个人觉得这里很不方便。如下:
static class MyAuthenticator extends Authenticator {
private String user = "";
private String password = "";
public MyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}
}
我们需要覆盖java.net.Authenticator类的getPasswordAuthentication()方法,并返回一个PasswordAuthentication实例。要使他起作用,还需要设置
// 设置登陆到代理服务器的用户名和密码
Authenticator.setDefault(new MyAuthenticator(proxyUser, proxyPass));
使用代理的方式是在打开Http连接的时候同时传递一个Proxy参数。如果需要验证信息的话我们可以添加一个Http头参数来实现。
//格式如: "Proxy-Authorization"= "Basic Base64.encode(user:password)"
String headerKey = "Proxy-Authorization";
String headerValue = "Basic " + Base64.encode(user+":"+password);
conn.setRequestProperty(headerKey, headerValue);
其中的Base64.encode(user:password)是指把用户名和密码用冒号连接起来之后使用Base64编码后的值作为值的一部分。
这样就可以正常代理啦,