RestTemplate技术预研-认识RestTemplate
驗證碼服務對外提供http接口,我們使用的postman和swagger-ui都屬于http客戶端的一種,使用它們可以調用驗證碼服務的接口獲取驗證碼。現在我們需要使用Java程序模擬http客戶端調用驗證碼服務的接口獲取驗證碼。
RestTemplate是Spring提供的用于訪問RESTful服務的客戶端,RestTemplate提供了多種便捷訪問遠程Http服務的方法,能夠大大提高客戶端的編寫效率。RestTemplate默認依賴JDK提供http連接的能力(HttpURLConnection),也可以通過替換為例如 Apache HttpComponents、Netty或OkHttp等其它HTTP 客戶端,OkHttp的性能優越,本項目使用OkHttp,官網:https://square.github.io/okhttp/,github:https://github.com/square/okhttp。
在工程中引入依賴:
<!‐‐ okhttp3依賴 ‐‐> <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId> </dependency>在父工程已規范了okhttp的版本
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.9.1</version> </dependency>在MerchantApplicationBootstrap類中添加RestTemplate初始化:
@Bean public RestTemplate restTemplate() {return new RestTemplate(new OkHttp3ClientHttpRequestFactory())??; }在test下創建測試程序如下:
使用RestTemplate獲取百度的網頁內容。
@SpringBootTest @RunWith(SpringRunner.class) @Slf4j public class RestTemplateTest {@AutowiredRestTemplate restTemplate;//測試使用restTemplate作為http的客戶端向http服務端發起請求@Testpublic void gethtml(){String url = "http://www.baidu.com/";//向url發送http請求,得到響應結果ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);String body = forEntity.getBody();System.out.println(body);}//向驗證碼服務發送請求,獲取驗證碼//http://localhost:56085/sailing/generate?effectiveTime=600&name=sms@Testpublic void getSmsCode(){String url = "http://localhost:56085/sailing/generate?effectiveTime=600&name=sms";//請求體Map<String,Object> body = new HashMap<>();body.put("mobile","133456");//請求頭HttpHeaders httpHeaders =new HttpHeaders();//指定Content-Type: application/jsonhttpHeaders.setContentType(MediaType.APPLICATION_JSON);//請求信息,傳入body,headerHttpEntity httpEntity = new HttpEntity(body,httpHeaders);//向url請求ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);log.info("請求驗證碼服務,得到響應:{}", JSON.toJSONString(exchange));Map bodyMap = exchange.getBody();System.out.println(bodyMap);Map result = (Map) bodyMap.get("result");String key = (String) result.get("key");System.out.println(key);} }通過測試發現可以成功獲取百度的網頁內容。
網頁內容中中文亂碼解決方案:
原因:
當RestTemplate默認使用String存儲body內容時默認使用ISO_8859_1字符集。
解決:
配置StringHttpMessageConverter 消息轉換器,使用utf-8字符集。
修改RestTemplate的定義方法
@Bean RestTemplate restTemplate(){RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());//得到消息轉換器List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();//指定StringHttpMessageConverter消息轉換器的字符集為utf-8messageConverters.set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));return restTemplate; }?
總結
以上是生活随笔為你收集整理的RestTemplate技术预研-认识RestTemplate的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 接口调试利器Postman
- 下一篇: ConcurrentHashMap的源码