给http请求设置代理,一下为参考代码和maven依赖。此处以Java中常用的Http工具包RestTemplate和OkHttp为例。
package com.huobi;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Objects;
import java.util.Optional;
/**
* hlTodo
*
* @author hulei
* @date 2021/3/19
*/
public class TestProxy {
public static void main(String[] args) {
// okClient();
restClient();
}
private static void restClient(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory(){{
setProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 10808)));
}});
// String baidu = "https://www.baidu.com";
String google = "https://www.google.com";
ResponseEntity<String> entity = restTemplate.getForEntity(google, String.class);
System.out.println(">>>" + entity.getBody());
}
private static void okClient() {
OkHttpClient httpClient = new OkHttpClient().newBuilder()
.proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 10808)))
.build();
// String baidu = "https://www.baidu.com";
String google = "https://www.google.com";
Request request = new Request.Builder().url(google).build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
System.out.println("failure");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
System.out.println("success >>> " + Optional.ofNullable(response.body()).orElseThrow(RuntimeException::new).string());
}
});
}
}
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.5.0</version>
</dependency>
</dependencies>
其中最重要的一段代码new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 10808))
,这里SOCKS是代理协议,例如常见的代理软件SS、vtoray都是使用Socks4/Socks5协议。
这里127.0.0.0
和10808
是我本地启动Vtoray后本地监听的端口,参见Vtoray:参数设置->基础设置。
所以以上代码生效的前提是需要找一个墙外的服务器部署上vtoray。
设置代理的作用是什么:我这里需要访问火币开放API查询个人账户信息,但是火币API网站明确写明不支持大陆IP,所以这里就需要通过代理去访问,经过测试https://api.huobi.pro
此域名在不配置Proxy的情况下是无法访问的。
原文:https://www.cnblogs.com/raifujisann/p/14593647.html