快速开始
在发送url请求时,使用该工具方便将获取的请求进行映射之类的操作,参数全部放在map对象中,使用HashMap进行封装
xxx xx = restTemplate.getForObject(url,xxx.class[,params])
xxx xx = restTemplate.postForObject(url,xxx.class[,data])
HashMap<String, String> map = new HashMap<>();
map.put("id",id);
String json = restTemplate.postForObject("http://abc.com/query",String.class,map)
// 返回json字符串
参考资料:
https://blog.csdn.net/itguangit/article/details/78825505
发送https
restTemplate可以接受一个public RestTemplate(ClientHttpRequestFactory requestFactory)
来初始化,可以自定义一个requestFactory类来实现发送https请求:
MySimpleHttpClient.java
public class MySimpleHttpClient extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("需要https的connection");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class MyCustomSSLSocketFactory extends SSLSocketFactory{
private final SSLSocketFactory delegate;
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
//
private Socket overrideProtocol(final Socket socket) {
if (!(socket instanceof SSLSocket)) {
throw new RuntimeException("An instance of SSLSocket is expected");
}
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
return socket;
}
}
}
然后初始化restTemplate实例:
RestTemplate https = new RestTemplate(new MySimpleHttpClient());
为了防止乱码,这里设置了字符编码格式:
List<HttpMessageConverter<?>> converterList = https.getMessageConverters();
converterList.remove(1); // 移除原来的转换器
// 设置字符编码为utf-8
HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
converterList.add(1, converter); // 添加新的转换器(注:convert顺序错误会导致失败)
https.setMessageConverters(converterList);
使用方式也很简单,和http一样:
String result = https.getForObject("https://www.baidu.com",String.class);
当然,为了实现https请求,可以使用第三方工具类来实现,比springboot自带的restTemplate更简单高效!
目前比较常用的是:httpclient和okhttp
httpclient
// get 方法 public String getHttps() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpsGet = new HttpGet("https://www.baidu.com"); CloseableHttpResponse resp = httpClient.execute(httpsGet); String result= EntityUtils.toString(resp.getEntity(),"utf-8"); resp.close(); return result; } // post 方法 // https://www.cnblogs.com/Mr-Rocker/p/6229652.html // https://www.cnblogs.com/ncy1/p/10668332.html
okhttp:该部分内容过多,单独开一文写_