一、使用场景
- 爬虫请求更换IP
- Fiddler抓取Java代码的Http请求(RestTemplate)
二、配置
配置RestTemplate
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(50000);//ms
factory.setConnectTimeout(150000);//ms
return factory;
}
}
封装接口
@Slf4j
public class RestUtil {
/**
* RestAPI 调用器
*/
private final static RestTemplate RT;
static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(300000);
requestFactory.setReadTimeout(300000);
RT = new RestTemplate(requestFactory);
// 解决乱码问题
RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
public static RestTemplate getRestTemplate() {
return RT;
}
public static void setRestTemplate(String ip, Integer port) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(50000);//ms
factory.setConnectTimeout(150000);//ms
factory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port)));
RT.setRequestFactory(factory);
// 解决乱码问题
RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
}
三、具体使用
在每次使用之前,使用RestUtil.setRestTemplate("203.66.65.6",3128)方法进行ip和端口的更换