文章目录
- 说明
- 原始HttpClient
- 代理HttpClient
- 总结
说明
在这篇文章中会对HttpClient5如何进行代理进行说明,我的HttpClient版本是5.2.1。在进行代理之前请先准备好代理服务器。
原始HttpClient
下面是没有进行代理设置的代码,尝试去访问openai接口
@Testpublic void t1() throws IOException {String url = "https://api.openai.com/v1/chat/completions";HttpPost httpPost = new HttpPost(url);try (CloseableHttpClient client = HttpClients.createDefault()) {client.execute(new HttpHost("api.openai.com"), httpPost, response -> {System.out.println(response);return null;});}}
运行这个代码,不出意外的运行失败了
代理HttpClient
在HttpClient比较早的版本是通过setProxy方法来进行代理设置的,但是现在这个方法已经废弃了
@Deprecatedpublic Builder setProxy(final HttpHost proxy) {this.proxy = proxy;return this;}
在现在的版本中我们应该使用DefaultProxyRoutePlanner,下面就是应该简单用法,在new的时候传入一个HttpHost即可,指定要代理的主机和端口
HttpHost proxy = new HttpHost("127.0.0.1", 7890);DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
下面的代码就使用代理去访问openai的接口
@Testpublic void t2() throws IOException {//要访问的网址String url = "https://api.openai.com/v1/chat/completions";HttpHost proxy = new HttpHost("127.0.0.1", 7890);DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);HttpPost httpPost = new HttpPost(url);try (CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build()) {client.execute(new HttpHost("api.openai.com"), httpPost, response -> {System.out.println(response);return null;});}}
使用的代理之后代码就能够访问openai的接口了
总结
使用代理其实很简单,就是调用下setRoutePlanner方法
CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build()
异步请求也是类似的
CloseableHttpAsyncClient asyncClient = HttpAsyncClients.custom().setRoutePlanner(routePlanner).build();