基于springboot的RestTemplate、okhttp和HttpClient对⽐
1、HttpClient:代码复杂,还得操⼼资源回收等。代码很复杂,冗余代码多,不建议直接使⽤。
2、RestTemplate:是 Spring 提供的⽤于访问Rest服务的客户端, RestTemplate 提供了多种便捷访问远程Http服务的⽅法,能够⼤⼤提⾼客户端的编写效率。
引⼊jar包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加初始化配置(也可以不配,有默认的)--注意RestTemplate只有初始化配置,没有什么连接池
package fig;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApiConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();//默认的是JDK提供http连接,需要的话可以//通过setRequestFactory⽅法替换为例如Apache HttpComponents、Netty或//OkHttp等其它HTTP library。 factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}
View Code
1)get请求(不带参的即把参数取消即可)
// 1-getForObject()
User user1 = ForObject(uri, User.class);
// 2-getForEntity()
ResponseEntity<User> responseEntity1 = ForEntity(uri, User.class);
HttpStatus statusCode = StatusCode();
HttpHeaders header = Headers();
User user2 = Body();
// 3-exchange()
RequestEntity requestEntity = (new URI(uri)).build();
ResponseEntity<User> responseEntity2 = hange(requestEntity, User.class);
User user3 = Body();
⽅式⼀:
Notice notice = ForObject("p/notice/list/{1}/{2}"
,
Notice.class,1,5);
⽅式⼆:
Map<String,String> map = new HashMap();
map.put("start","1");
map.put("page","5");
Notice notice = ForObject("p/notice/list/"
, Notice.class,map);
2)post请求:
// 1-postForObject()
User user1 = stTemplate.postForObject(uri, user, User.class);
// 2-postForEntity()
ResponseEntity<User> responseEntity1 = stTemplate.postForEntity(uri, user, User.class);
// 3-exchange()
RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user);
ResponseEntity<User> responseEntity2 = hange(requestEntity, User.class);
⽅式⼀:
String url = "demo/api/book/";
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
String requestJson = "{...}";
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String result = restTemplate.postForObject(url, entity, String.class);
System.out.println(result);
⽅式⼆:
@Test
public void rtPostObject(){
RestTemplate restTemplate = new RestTemplate();
String url = "96/register/checkEmail";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("email", "844072586@qq");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
System.out.Body());
}
其它:还⽀持上传和下载功能;
3、okhttp:OkHttp是⼀个⾼效的HTTP客户端,允许所有同⼀个主机地址的请求共享同⼀个socket连接;连接池减少请求延时;透明的GZIP压缩减少响应数据的⼤⼩;缓存响应内容,避免⼀些完全重复的请求
当⽹络出现问题的时候OkHttp依然坚守⾃⼰的职责,它会⾃动恢复⼀般的连接问题,如果你的服务有多个IP地址,当第⼀个IP请求失败时,OkHttp会交替尝试你配置的其他IP,OkHttp使⽤现代TLS技术(SNI, ALPN)初始化新的连接,当握⼿失败时会回退到TLS 1.0。
1)使⽤:它的请求/响应 API 使⽤构造器模式builders来设计,它⽀持阻塞式的同步请求和带回调的异步请求。
引⼊jar包:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
2)配置⽂件:
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import t.annotation.Bean;
import t.annotation.Configuration;
import javax.ssl.SSLContext;
import javax.ssl.SSLSocketFactory;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import CertificateException;
import X509Certificate;
import urrent.TimeUnit;
@Configuration
public class OkHttpConfiguration {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
//.sslSocketFactory(sslSocketFactory(), x509TrustManager())
.retryOnConnectionFailure(false)
.connectionPool(pool())
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30,TimeUnit.SECONDS)
.build();
}
@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
//信任任何链接
SSLContext sslContext = Instance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
SocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
/**
* Create a new connection pool with tuning parameters appropriate for a single-user application.
* The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
*/
@Bean
public ConnectionPool pool() {
return new ConnectionPool(200, 5, TimeUnit.MINUTES);
}
}
3)util⼯具:
import okhttp3.*;
import org.ption.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
public class OkHttpUtil{
private static final Logger logger = Logger(OkHttpUtil.class);
private static OkHttpClient okHttpClient;
@Autowired
public OkHttpUtil(OkHttpClient okHttpClient) {
OkHttpUtil.okHttpClient= okHttpClient;
}
/
**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后⾯的数据,没有可以传null
* @return
*/
public static String get(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = Set().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) ();
if (firstFlag) {
sb.append("?" + Key() + "=" + Value());
firstFlag = false;
} else {
sb.append("&" + Key() + "=" + Value());
}
}
}
Request request = new Request.Builder()
.String())
.build();
Response response = null;
try {
response = wCall(request).execute();
int status = de();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
<("okhttp3 put error >> ex = {}", StackTrace(e)); } finally {
if (response != null) {
response.close();
}
}
return responseBody;spring framework和spring的关系
}
/**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public static String post(String url, Map<String, String> params) {
String responseBody = "";
FormBody.Builder builder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, (key));
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
Response response = null;
try {
response = wCall(request).execute();
int status = de();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
<("okhttp3 post error >> ex = {}", StackTrace(e)); } finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后⾯的数据,没有可以传null
* @return
*/
public static String getForHeader(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = Set().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) ();
if (firstFlag) {
sb.append("?" + Key() + "=" + Value());
firstFlag = false;
} else {
sb.append("&" + Key() + "=" + Value());
}
}
}
Request request = new Request.Builder()
.addHeader("key", "value")
.
String())
.build();
Response response = null;
try {
response = wCall(request).execute();
int status = de();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
<("okhttp3 put error >> ex = {}", StackTrace(e)); } finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数⼀:请求Url
* 参数⼆:请求的JSON
* 参数三:请求回调
*/
public static String postJsonParams(String url, String jsonParams) {
String responseBody = "";
RequestBody requestBody = ate(MediaType.parse("application/json; charset=utf-8"), jsonParams); Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = null;
try {
response = wCall(request).execute();
int status = de();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
<("okhttp3 post error >> ex = {}", StackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* Post请求发送xml数据....
* 参数⼀:请求Url
* 参数⼆:请求的xmlString
* 参数三:请求回调
*/
public static String postXmlParams(String url, String xml) {
String responseBody = "";
RequestBody requestBody = ate(MediaType.parse("application/xml; charset=utf-8"), xml);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = null;
try {
response = wCall(request).execute();
int status = de();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
<("okhttp3 post error >> ex = {}", StackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论