SpringBoot中RestTemplate基本封裝
阿新 • • 發佈:2020-11-29
核心配置,注入RestTemplate為Bean
package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class HttpConfig { /** * 兩分鐘超時時間 */ private int outtime = 2 * 60 * 1000; @Bean public RestTemplate restTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(outtime); requestFactory.setReadTimeout(outtime); return new RestTemplate(); } }
封裝GET/POST請求
package com.example.demo.service; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.Map; /** * Http請求Service */ @Service public class HttpService { @Autowired private RestTemplate restTemplate; /** * get請求 * * @param url 請求地址 * @param headerMap 頭部資訊 * @param resp 響應結果型別 * @return */ public Object get(String url, Map<String, String> headerMap, Class<?> resp) { HttpHeaders httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> stringStringEntry : headerMap.entrySet()) { httpHeaders.add(stringStringEntry.getKey(), stringStringEntry.getValue()); } HttpEntity httpEntity = new HttpEntity(httpHeaders); ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.GET, httpEntity, resp); return result.getBody(); } /** * post 請求 * * @param url 請求地址 * @param headerMap 頭資訊 * @param jsonObject 請求引數 JSON * @return JSONObject */ public JSONObject post(String url, Map<String, String> headerMap, JSONObject jsonObject) { HttpHeaders httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> stringStringEntry : headerMap.entrySet()) { httpHeaders.add(stringStringEntry.getKey(), stringStringEntry.getValue()); } HttpEntity httpEntity = new HttpEntity(jsonObject, httpHeaders); JSONObject result = restTemplate.postForObject(url, httpEntity, JSONObject.class); return result; } }
測試HttpService
/** * 測試get */ @Test public void getService() { Map<String, String> map = new HashMap<>(); map.put("abc", "23434"); String obj = (String) httpService.get("http://127.0.0.1:8080/b", map, String.class); System.out.println(obj); }/** * 測試post */ @Test public void postService() { Map<String, String> map = new HashMap<>(); map.put("abc", "54545"); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "孫悟空"); JSONObject obj = httpService.post("http://127.0.0.1:8080/a", map, jsonObject); System.out.println(obj); }