java常见的http请求库有httpclient,RestTemplate,OKhttp,更高层次封装的 feign、retrofit
##1、HttpClient HttpClient:代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,不建议直接使用。
##2、RestTemplate RestTemplate: 是 Spring 提供的用于访问Rest服务的客户端, RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
引入jar包:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency>
添加初始化配置(也可以不配,有默认的)--注意RestTemplate只有初始化配置,没有什么连接池
1package com.itunion.config; 2 3import org.springframework.context.annotation.Bean; 4import org.springframework.context.annotation.Configuration; 5import org.springframework.http.client.ClientHttpRequestFactory; 6import org.springframework.http.client.SimpleClientHttpRequestFactory; 7import org.springframework.web.client.RestTemplate; 8 9@Configuration 10public class ApiConfig { 11 @Bean 12 public RestTemplate restTemplate(ClientHttpRequestFactory factory) { 13 return new RestTemplate(factory); 14 } 15 16 @Bean 17 public ClientHttpRequestFactory simpleClientHttpRequestFactory() { 18 SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();//默认的是JDK提供http连接,需要的话可以//通过setRequestFactory方法替换为例如Apache HttpComponents、Netty或//OkHttp等其它HTTP library。 19 factory.setReadTimeout(5000);//单位为ms 20 factory.setConnectTimeout(5000);//单位为ms 21 return factory; 22 } 23}
####(1)get请求(不带参的即把参数取消即可)
1// 1-getForObject() 2User user1 = this.restTemplate.getForObject(uri, User.class); 3 4// 2-getForEntity() 5ResponseEntity<User> responseEntity1 = this.restTemplate.getForEntity(uri, User.class); 6HttpStatus statusCode = responseEntity1.getStatusCode(); 7HttpHeaders header = responseEntity1.getHeaders(); 8User user2 = responseEntity1.getBody(); 9 10// 3-exchange() 11RequestEntity requestEntity = RequestEntity.get(new URI(uri)).build(); 12ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class); 13User user3 = responseEntity2.getBody();
方式一:
1Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}" 2 , Notice.class,1,5);
方式二:
1Map<String,String> map = new HashMap(); 2 map.put("start","1"); 3 map.put("page","5"); 4 Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/" 5 , Notice.class,map);
####(2)post请求:
1// 1-postForObject() 2User user1 = this.restTemplate.postForObject(uri, user, User.class); 3 4// 2-postForEntity() 5ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class); 6 7// 3-exchange() 8RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user); 9ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
方式一:
1String url = "http://demo/api/book/"; 2 HttpHeaders headers = new HttpHeaders(); 3 MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); 4 headers.setContentType(type); 5 String requestJson = "{...}"; 6 HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers); 7 String result = restTemplate.postForObject(url, entity, String.class); 8 System.out.println(result);
方式二:
1@Test 2public void rtPostObject(){ 3 RestTemplate restTemplate = new RestTemplate(); 4 String url = "http://47.xxx.xxx.96/register/checkEmail"; 5 HttpHeaders headers = new HttpHeaders(); 6 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); 7 MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); 8 map.add("email", "844072586@qq.com"); 9 10 HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); 11 ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class ); 12 System.out.println(response.getBody()); 13}
其它:还支持上传和下载功能;
##3、okhttp okhttp:OkHttp是一个高效的HTTP客户端,允许所有同一个主机地址的请求共享同一个socket连接;连接池减少请求延时;透明的GZIP压缩减少响应数据的大小;缓存响应内容,避免一些完全重复的请求
当网络出现问题的时候OkHttp依然坚守自己的职责,它会自动恢复一般的连接问题,如果你的服务有多个IP地址,当第一个IP请求失败时,OkHttp会交替尝试你配置的其他IP,OkHttp使用现代TLS技术(SNI, ALPN)初始化新的连接,当握手失败时会回退到TLS 1.0。
####(1)使用:它的请求/响应 API 使用构造器模式builders来设计,它支持阻塞式的同步请求和带回调的异步请求。
引入jar包:
1<dependency> 2 <groupId>com.squareup.okhttp3</groupId> 3 <artifactId>okhttp</artifactId> 4 <version>3.10.0</version> 5</dependency>
####(2)配置文件:
1import okhttp3.ConnectionPool; 2import okhttp3.OkHttpClient; 3import org.springframework.context.annotation.Bean; 4import org.springframework.context.annotation.Configuration; 5 6import javax.net.ssl.SSLContext; 7import javax.net.ssl.SSLSocketFactory; 8import javax.net.ssl.TrustManager; 9import javax.net.ssl.X509TrustManager; 10import java.security.KeyManagementException; 11import java.security.NoSuchAlgorithmException; 12import java.security.SecureRandom; 13import java.security.cert.CertificateException; 14import java.security.cert.X509Certificate; 15import java.util.concurrent.TimeUnit; 16 17@Configuration 18public class OkHttpConfiguration { 19 20 @Bean 21 public OkHttpClient okHttpClient() { 22 return new OkHttpClient.Builder() 23 //.sslSocketFactory(sslSocketFactory(), x509TrustManager()) 24 .retryOnConnectionFailure(false) 25 .connectionPool(pool()) 26 .connectTimeout(30, TimeUnit.SECONDS) 27 .readTimeout(30, TimeUnit.SECONDS) 28 .writeTimeout(30,TimeUnit.SECONDS) 29 .build(); 30 } 31 32 @Bean 33 public X509TrustManager x509TrustManager() { 34 return new X509TrustManager() { 35 @Override 36 public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { 37 } 38 @Override 39 public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { 40 } 41 @Override 42 public X509Certificate[] getAcceptedIssuers() { 43 return new X509Certificate[0]; 44 } 45 }; 46 } 47 48 @Bean 49 public SSLSocketFactory sslSocketFactory() { 50 try { 51 //信任任何链接 52 SSLContext sslContext = SSLContext.getInstance("TLS"); 53 sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom()); 54 return sslContext.getSocketFactory(); 55 } catch (NoSuchAlgorithmException e) { 56 e.printStackTrace(); 57 } catch (KeyManagementException e) { 58 e.printStackTrace(); 59 } 60 return null; 61 } 62 63 /** 64 * Create a new connection pool with tuning parameters appropriate for a single-user application. 65 * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently 66 */ 67 @Bean 68 public ConnectionPool pool() { 69 return new ConnectionPool(200, 5, TimeUnit.MINUTES); 70 } 71}
####(3)util工具:
1import okhttp3.*; 2import org.apache.commons.lang3.exception.ExceptionUtils; 3import org.slf4j.Logger; 4import org.slf4j.LoggerFactory; 5 6import java.io.File; 7import java.util.Iterator; 8import java.util.Map; 9 10public class OkHttpUtil{ 11 private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class); 12 13 private static OkHttpClient okHttpClient; 14 15 @Autowired 16 public OkHttpUtil(OkHttpClient okHttpClient) { 17 OkHttpUtil.okHttpClient= okHttpClient; 18 } 19 20 /** 21 * get 22 * @param url 请求的url 23 * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null 24 * @return 25 */ 26 public static String get(String url, Map<String, String> queries) { 27 String responseBody = ""; 28 StringBuffer sb = new StringBuffer(url); 29 if (queries != null && queries.keySet().size() > 0) { 30 boolean firstFlag = true; 31 Iterator iterator = queries.entrySet().iterator(); 32 while (iterator.hasNext()) { 33 Map.Entry entry = (Map.Entry<String, String>) iterator.next(); 34 if (firstFlag) { 35 sb.append("?" + entry.getKey() + "=" + entry.getValue()); 36 firstFlag = false; 37 } else { 38 sb.append("&" + entry.getKey() + "=" + entry.getValue()); 39 } 40 } 41 } 42 Request request = new Request.Builder() 43 .url(sb.toString()) 44 .build(); 45 Response response = null; 46 try { 47 response = okHttpClient.newCall(request).execute(); 48 int status = response.code(); 49 if (response.isSuccessful()) { 50 return response.body().string(); 51 } 52 } catch (Exception e) { 53 logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e)); 54 } finally { 55 if (response != null) { 56 response.close(); 57 } 58 } 59 return responseBody; 60 } 61 62 /** 63 * post 64 * 65 * @param url 请求的url 66 * @param params post form 提交的参数 67 * @return 68 */ 69 public static String post(String url, Map<String, String> params) { 70 String responseBody = ""; 71 FormBody.Builder builder = new FormBody.Builder(); 72 //添加参数 73 if (params != null && params.keySet().size() > 0) { 74 for (String key : params.keySet()) { 75 builder.add(key, params.get(key)); 76 } 77 } 78 Request request = new Request.Builder() 79 .url(url) 80 .post(builder.build()) 81 .build(); 82 Response response = null; 83 try { 84 response = okHttpClient.newCall(request).execute(); 85 int status = response.code(); 86 if (response.isSuccessful()) { 87 return response.body().string(); 88 } 89 } catch (Exception e) { 90 logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e)); 91 } finally { 92 if (response != null) { 93 response.close(); 94 } 95 } 96 return responseBody; 97 } 98 99 /** 100 * get 101 * @param url 请求的url 102 * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null 103 * @return 104 */ 105 public static String getForHeader(String url, Map<String, String> queries) { 106 String responseBody = ""; 107 StringBuffer sb = new StringBuffer(url); 108 if (queries != null && queries.keySet().size() > 0) { 109 boolean firstFlag = true; 110 Iterator iterator = queries.entrySet().iterator(); 111 while (iterator.hasNext()) { 112 Map.Entry entry = (Map.Entry<String, String>) iterator.next(); 113 if (firstFlag) { 114 sb.append("?" + entry.getKey() + "=" + entry.getValue()); 115 firstFlag = false; 116 } else { 117 sb.append("&" + entry.getKey() + "=" + entry.getValue()); 118 } 119 } 120 } 121 Request request = new Request.Builder() 122 .addHeader("key", "value") 123 .url(sb.toString()) 124 .build(); 125 Response response = null; 126 try { 127 response = okHttpClient.newCall(request).execute(); 128 int status = response.code(); 129 if (response.isSuccessful()) { 130 return response.body().string(); 131 } 132 } catch (Exception e) { 133 logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e)); 134 } finally { 135 if (response != null) { 136 response.close(); 137 } 138 } 139 return responseBody; 140 } 141 142 /** 143 * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 144 * 参数一:请求Url 145 * 参数二:请求的JSON 146 * 参数三:请求回调 147 */ 148 public static String postJsonParams(String url, String jsonParams) { 149 String responseBody = ""; 150 RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams); 151 Request request = new Request.Builder() 152 .url(url) 153 .post(requestBody) 154 .build(); 155 Response response = null; 156 try { 157 response = okHttpClient.newCall(request).execute(); 158 int status = response.code(); 159 if (response.isSuccessful()) { 160 return response.body().string(); 161 } 162 } catch (Exception e) { 163 logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e)); 164 } finally { 165 if (response != null) { 166 response.close(); 167 } 168 } 169 return responseBody; 170 } 171 172 /** 173 * Post请求发送xml数据.... 174 * 参数一:请求Url 175 * 参数二:请求的xmlString 176 * 参数三:请求回调 177 */ 178 public static String postXmlParams(String url, String xml) { 179 String responseBody = ""; 180 RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml); 181 Request request = new Request.Builder() 182 .url(url) 183 .post(requestBody) 184 .build(); 185 Response response = null; 186 try { 187 response = okHttpClient.newCall(request).execute(); 188 int status = response.code(); 189 if (response.isSuccessful()) { 190 return response.body().string(); 191 } 192 } catch (Exception e) { 193 logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e)); 194 } finally { 195 if (response != null) { 196 response.close(); 197 } 198 } 199 return responseBody; 200 } 201}