早期的 HttpURLConnection 使用非常繁瑣,得寫很多代碼實現一個簡單的請求,而 HttpClient 簡單很多,不過此種方法使用起來太過繁瑣,需要進行各種序列化和反序列化。RestTemplate 進一步簡化,它可以像OkHttp那樣的寫法,但是常見的請求基本一句代碼就可以搞定。
使用RestTemplate方法,pom.xml文件幾乎不用添加配置
<properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.3.7.RELEASE</spring-boot.version> <fastjson.version>1.2.47</fastjson.version> </properties> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency>
- 創建配置類RestTemplateConfig
package com.resttemp.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.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(15000); factory.setReadTimeout(5000); return factory; } }
- 創建代理服務類
package com.resttemp.demo.proxy; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; @Service public class ARestTemplate { @Autowired private RestTemplate restTemplate; /** * 以get方式請求第三方http接口 getForEntity * @param url * @return */ public String doGetEnity1(String url){ ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); String riskmerchantself = responseEntity.getBody(); return riskmerchantself; } /** * 以get方式請求第三方http接口 getForObject * 返回值返回的是響應體,省去了我們再去getBody() * @param url * @return */ public String doGetForObj1(String url){ String riskmerchantself = restTemplate.getForObject(url, String.class); return riskmerchantself; } /** * 以post方式請求第三方http接口 postForEntity * @param url * @return */ public String doPostForEnity1(String url){ // 設置請求頭 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json;charset=utf-8"); //設置請求參數 Map<String, Object> postData = new HashMap<>(); postData.put("merchant_name", "model1"); //將請求頭和請求參數設置到HttpEntity中 HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(postData, httpHeaders); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class); String body = responseEntity.getBody(); return body; } /** * 以post方式請求第三方http接口 postForEntity * @param url * @return */ public String doPostForObj1(String url){ // 設置請求頭 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json;charset=utf-8"); //設置請求參數 Map<String, Object> postData = new HashMap<>(); postData.put("merchant_name", "model1"); //將請求頭和請求參數設置到HttpEntity中 HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(postData, httpHeaders); String body = restTemplate.postForObject(url, httpEntity, String.class); return body; } /** * exchange * @return */ public String doExchange(String url){ //header參數 HttpHeaders headers = new HttpHeaders(); String token = "qqqqq"; headers.add("authorization", token); headers.setContentType(MediaType.APPLICATION_JSON); //放入body中的json參數 JSONObject obj = new JSONObject(); obj.put("merchant_name", "model exchange"); //組裝 HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers); ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class); String body = responseEntity.getBody(); return body; } }
- controller層調用
package com.resttemp.demo.controller; import com.resttemp.demo.proxy.ARestTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/a") public class AController { @Autowired private ARestTemplate aRestTemplate; @GetMapping("/doGetEnity1") public String doGetEnity1(){ try{ String result= aRestTemplate.doGetEnity1("https:/***ById?id=3"); System.out.println(result); return result; }catch (Exception e){ return e.getMessage(); } } @GetMapping("/doGetForObj1") public String doGetForObj1(){ try{ String result= aRestTemplate.doGetForObj1("https:/***ById?id=4"); System.out.println(result); return result; }catch (Exception e){ return e.getMessage(); } } @PostMapping("/doPostForEnity1") public String doPostForEnity1(){ try{ String result= aRestTemplate.doPostForEnity1("https:/***/Save"); System.out.println("jsonobject:"+result); return result; }catch (Exception e){ return e.getMessage(); } } @PostMapping("/doPostForObj1") public String doPostForObj1(){ try{ String result= aRestTemplate.doPostForObj1("https:/***/Save"); System.out.println("jsonobject:"+result); return result; }catch (Exception e){ return e.getMessage(); } } @PostMapping("/doExchange") public String doExchange(){ try { String result = aRestTemplate.doExchange("https:/***/Save"); System.out.println("jsonobject:" + result); return result; } catch (Exception e) { return e.getMessage(); } } }
完整目錄結構如下