一开始以为是ssl证书的问题。在百度上找了半天,千篇一律都是在resttemplate实例化时加忽略证书。当然我也是加了忽略证书的,但是还是一直报那个错…
最后找到原因: 因为我访问的是国外的网站,我设置的代理ip是本机127.0.0.1;所以网络一直掉不通。
解决: 配置文件中将地址改为使用代理服务器的ip端口就可以了(没有可以买一个或者挂梯子)
下面附上完整的resttemplateutils实例化代码:
@component
public class resttemplateutils {
private static httpproxyproperties httpproxyproperties;
resttemplateutils(httpproxyproperties properties) {
httpproxyproperties = properties;
}
@sneakythrows
public static resttemplate getinstance(string charset) {
truststrategy acceptingtruststrategy = (x509certificate[] chain, string authtype) -> true;
//忽略证书
sslcontext sslcontext = org.apache.http.ssl.sslcontexts.custom()
.loadtrustmaterial(null, acceptingtruststrategy)
.build();
sslconnectionsocketfactory csf = new sslconnectionsocketfactory(sslcontext);
registry<connectionsocketfactory> registry = registrybuilder.<connectionsocketfactory>create()
.register("http", plainconnectionsocketfactory.getsocketfactory())
.register("https", csf)
.build();
poolinghttpclientconnectionmanager connectionmanager = new poolinghttpclientconnectionmanager(registry);
//连接池的最大连接数,0代表不限;如果取0,需要考虑连接泄露导致系统崩溃的后果
connectionmanager.setmaxtotal(1000);
//每个路由的最大连接数,如果只调用一个地址,可以将其设置为最大连接数
connectionmanager.setdefaultmaxperroute(300);
httpclientbuilder clientbuilder = httpclients.custom();
if (objects.nonnull(httpproxyproperties) && boolean.true.equals(httpproxyproperties.getenabled())) {
httphost proxy = new httphost(httpproxyproperties.getip(), httpproxyproperties.getport());
clientbuilder.setproxy(proxy);
}
closeablehttpclient httpclient = clientbuilder.setconnectionmanager(connectionmanager)
.build();
httpcomponentsclienthttprequestfactory requestfactory =
new httpcomponentsclienthttprequestfactory();
requestfactory.sethttpclient(httpclient);
requestfactory.setconnectionrequesttimeout(10000);
requestfactory.setconnecttimeout(10000);
requestfactory.setreadtimeout(30000);
resttemplate resttemplate = new resttemplate(requestfactory);
list<httpmessageconverter<?>> list = resttemplate.getmessageconverters();
for (httpmessageconverter<?> httpmessageconverter : list) {
if (httpmessageconverter instanceof stringhttpmessageconverter) {
((stringhttpmessageconverter) httpmessageconverter).setdefaultcharset(charset.forname(charset));
break;
}
}
return resttemplate;
}
}
httpproxyproperties代码:
@data
@component
@configurationproperties(prefix = "http.proxy")
public class httpproxyproperties {
private boolean enabled;
private string ip;
private integer port;
}
使用:
private static resttemplate resttemplate = resttemplateutils.getinstance("utf-8");
问题解决,希望能够帮到你
发表评论