RestTemplate 设置代理
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.net.InetSocketAddress;
import java.net.Proxy;
@Configuration
public class RestConfig {
// 不添加代理
@Bean
public RestTemplate normal() {
return new RestTemplate();
}
// 添加代理
@Bean
public RestTemplate proxy() {
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
simpleClientHttpRequestFactory.setProxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("IP",IP.port))); // 添加代理 ip 和 port 即可
restTemplate.setRequestFactory(simpleClientHttpRequestFactory);
return restTemplate;
}
}
另:IDEA 如果也需要通过代理访问外网(例如,下载组件和插件)
设置:File -> Settings -> Appearance & Behavior -> System Settings -> HTTP Proxy
|