正向代理
正向代理是客户端的代理,帮助客户端访问其无法访问的服务器资源。比如我通过一个代理服务器可以访问很多国内无法访问的网站
反向代理
反向代理则是服务器的代理,帮助服务器做负载均衡,安全防护等。所有的用户都访问同一个网址,而我可以用多台服务器来处理这一个网址接收的请求
使用代理发送HTTP请求
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5-fluent -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-fluent</artifactId>
<version>5.2.1</version>
</dependency>
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpHost;
import java.net.URI;
import java.util.Base64;
public static void main(String[] args) throws Exception {
String target = "http://www.baidu.com";
URI proxyURI = new URI("http://代理用户名:代理密码@代理服务器:端口号");
String basicAuth = new String(Base64.getEncoder().encode(proxyURI.getUserInfo().getBytes()));
String response = Request.get(target)
.addHeader("Proxy-Authorization", "Basic " + basicAuth)
.viaProxy(HttpHost.create(proxyURI))
.execute()
.returnContent()
.asString();
System.out.println(response);
}