Springboot 之 RestTemplate的使用方法
1.maven 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2.RestTemplate 配置
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); //客户端与服务端建立连接超时时间 factory.setConnectTimeout(60000); //客户端从服务端读取数据的超时时间 factory.setReadTimeout(60000); return factory; } }
3.封装工具类
@Component public class HttpRequestHelper { @Resource private RestTemplate restTemplate; //一些自定义的请求头参数 public static final String supplierID = ""; public static final String interfacekey = ""; /** * get请求 返回 string * * @param url 请求的url * @param jsonData 请求的json * @return */ public String restGet(String url, String jsonData) { return request(url, jsonData, HttpMethod.GET); } /** * Get请求获取实体类 * * @param url 请求的url * @param responseType 返回的类型 * @param parms 不限定个数的参数 * @param <T> 泛型 * @return */ public <T> T getForEntity(String url, Class<T> responseType, Object... parms) { return (T) restTemplate.getForEntity(url, responseType, parms); } /** * Get请求 * * @param url * @param parm * @return */ public String get(String url, Map<String, Object> parm) { return restTemplate.getForEntity(url, String.class, parm).getBody(); } /** * @param url 请求的url * @param jsonData json数据 * @param httpMethod * @return */ private String request(String url, String jsonData, HttpMethod httpMethod) { ResponseEntity<String> response = null; try { HttpEntity<String> requestEntity = new HttpEntity<String>(jsonData); response = restTemplate.exchange(url, httpMethod, requestEntity, String.class); } catch (Exception ex) { ex.printStackTrace(); return ""; } return response.getBody().toString(); } /** * DLT专用执行方法 * * @param param 请求参数:可以添加一些常量请求值 * @param url 访问的url * @param method 请求的方法 * @return */ private String execute(Map<String, Object> param, String url, HttpMethod method) { HttpHeaders headers = this.getDefaultHeader(); Map<String, Object> requestor = this.getDefaultParam(); param.put("requestor", requestor); param.put("supplierID", supplierID); HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(param, headers); ResponseEntity<String> response = restTemplate.exchange(url, method, requestEntity, String.class); return response.getBody(); } /** * 获取默认的头请求信息 */ private HttpHeaders getDefaultHeader() { String timestamp = "" + System.currentTimeMillis(); String signature = EncoderByMd5(supplierID + timestamp + interfacekey); HttpHeaders headers = new HttpHeaders(); headers.add("signature", signature); headers.add("timestamp", timestamp); return headers; } /** * 获取默认的参数 */ private Map<String, Object> getDefaultParam() { Map<String, Object> defParam = new HashMap<>(); defParam.put("invoker", "xx"); defParam.put("operatorName", "xx"); return defParam; } /** * 通过MD5加密 * * @param str * @return */ public static String EncoderByMd5(String str) { if (str == null) { return null; } try { // 确定计算方法 MessageDigest md5 = MessageDigest.getInstance("MD5"); BASE64Encoder base64en = new BASE64Encoder(); // 加密后的字符串 return base64en.encode(md5.digest(str.getBytes("utf-8"))).toUpperCase(); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { return null; } } /** * 文件上传 * @param file * @param url */ public void upload(File file,String url){ HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/octet-stream"); // File file = new File("/tmp/1.jpeg"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] fileByte = outputStream.toByteArray(); // 请求体 HttpEntity<byte[]> entity = new HttpEntity<byte[]>(fileByte, headers); RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>(); requestParams.add("expires", "259200"); requestParams.add("dir", "filepath"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParams(requestParams); restTemplate.postForObject(builder.toUriString(), entity, Object.class); }
public List<T> getList(String url,HttpMethod httpMethod){
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity httpEntity = new HttpEntity(headers);
ResponseEntity<List<T>> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<List<T>>() {});
return response.getBody();
}
}
4.单元测试
@Slf4j @SpringBootTest public class RestTemplateTest { @Resource private HttpRequestHelper httpRequestHelper; @Test public void test_rest() { String url="http://localhost:8090/blog"; //组装请求参数 Map<String,Object> parmMap =new HashMap<String,Object>(); String result = httpRequestHelper.get(url, parmMap); System.out.println(result); } }
5. 扩展工具类
package com.fescoadecco.util; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; @Slf4j public class HttpUtil { private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded"; private static final String CONTENT_TYPE_VALUE_JSON = "application/json"; private static RestTemplate restTemplate; /** *定义restTemplate * @param client */ public static void setRestTemplate(RestTemplate client) { restTemplate = client; } /** * get/post请求 * @param url * @param method * @param params * @return */ public static String client(String url, HttpMethod method, MultiValueMap<String, Object> params) { Map<String, String> setHeaders = new HashMap<>(); setHeaders.put(CONTENT_TYPE, CONTENT_TYPE_VALUE); return client(url, method, params, setHeaders); } /** * post请求 * @param url * @param params * @return */ public static String postClient(String url, Map<String, Object> params) { Map<String, String> setHeaders = new HashMap<>(); setHeaders.put(CONTENT_TYPE, CONTENT_TYPE_VALUE); return clientJson(url, HttpMethod.POST, params, setHeaders); } /** * get请求 * @param url * @param params * @return */ public static String getClient(String url, Map<String, Object> params) { Map<String, String> setHeaders = new HashMap<>(); setHeaders.put(CONTENT_TYPE, CONTENT_TYPE_VALUE); return clientJson(url, HttpMethod.GET, params, setHeaders); } /** * get/post请求 * @param url * @param method * @param params * @return */ public static String clientJson(String url, HttpMethod method, Map<String, Object> params) { Map<String, String> setHeaders = new HashMap<>(); setHeaders.put(CONTENT_TYPE, CONTENT_TYPE_VALUE_JSON); return clientJson(url, method, params, setHeaders); } /** * post请求 * @param url * @param params * @return */ public static String postClientJson(String url, Map<String, Object> params) { Map<String, String> setHeaders = new HashMap<>(); setHeaders.put(CONTENT_TYPE, CONTENT_TYPE_VALUE_JSON); return clientJson(url, HttpMethod.POST, params, setHeaders); } /** * get请求 * @param url * @param params * @return */ public static String getClientJson(String url, Map<String, Object> params) { Map<String, String> setHeaders = new HashMap<>(); setHeaders.put(CONTENT_TYPE, CONTENT_TYPE_VALUE_JSON); return clientJson(url, HttpMethod.GET, params, setHeaders); } /** * form请求 * * @param url * @param method * @param params MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); * map.add("test", "test_param"); * @return */ public static String client(String url, HttpMethod method, MultiValueMap<String, Object> params, Map<String, String> headers) { log.info("url:" + url + ",params:" + params + ",headers:" + headers); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params, setHeaders(headers)); ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, httpEntity, String.class, params); log.info("res_code:" + responseEntity.getStatusCode()); return JsonUtils.stringify(responseEntity.getBody()); } /** * json请求 * * @param url * @param method * @param params * @param headers * @return */ public static String clientJson(String url, HttpMethod method, Map<String, Object> params, Map<String, String> headers) { log.info("url:" + url + ",params:" + params + ",headers:" + headers); HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(params, setHeaders(headers)); ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, httpEntity, String.class, params); log.info("res_code:" + responseEntity.getStatusCode()); return JsonUtils.stringify(responseEntity.getBody()); } /** * 设置请求header * * @param Headers * @return */ public static HttpHeaders setHeaders(Map<String, String> Headers) { HttpHeaders httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> entry : Headers.entrySet()) { httpHeaders.add(entry.getKey(), entry.getValue()); } return httpHeaders; } }
6. 返回集合
@Test public void testRestTemplate() { String url="http://localhost:8090/blog"; // //组装请求参数 HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); HttpEntity httpEntity = new HttpEntity(headers); ResponseEntity<List<MysqlBlog>> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<List<MysqlBlog>>() {}); List<MysqlBlog> body = response.getBody(); System.out.println(body); }
7.GET进一步使用方式
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42", "21"); Map<String, String> vars = Collections.singletonMap("hotel", "42"); String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);
8.POST 使用方式
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<String, String>(); bodyMap.setAll(urlVariables); ResponseClass responseClass = restTemplate.postForObject(CAR_CES_URL, bodyMap, ResponseClass.class); //更完整的: HttpHeaders headers = new HttpHeaders(); headers.add("X-Auth-Token", "e348bc22-5efa-4299-9142-529f07a18ac9"); MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>(); postParameters.add("owner", "11"); postParameters.add("subdomain", "aoa"); postParameters.add("comment", ""); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers); ParseResultVo exchange = null; try { exchange = restTemplate.postForObject("http://demo", requestEntity, ParseResultVo.class); logger.info(exchange.toString()); } catch (RestClientException e) { logger.info("。。。。"); }
9.异步调用(AsyncRestTemplate)
public String asyncReq(){ String url = "http://localhost:8080/jsonAsync"; ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class); future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() { public void onSuccess(ResponseEntity<JSONObject> result) { System.out.println(result.getBody().toJSONString()); } }, new FailureCallback() { public void onFailure(Throwable ex) { System.out.println("onFailure:"+ex); } }); return "this is async sample"; } 我这里使用的是futrue,可以带返回参数的。这是java多线程中的一部分内容。如果有时间我会另起一篇简单的说下Java的多线程。