Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法
一、HttpClient
兩個(gè)系統(tǒng)間如何互相訪問??jī)蓚€(gè)tomcat上的項(xiàng)目如何互相訪問?
采用HttpClient實(shí)現(xiàn)跨系統(tǒng)的接口調(diào)用。
介紹:
官網(wǎng):http://hc.apache.org/index.html
現(xiàn)在也叫:HttpComponents
HttpClient可以發(fā)送get、post、put、delete、...等請(qǐng)求
使用:
導(dǎo)入坐標(biāo)
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency>
//1、使用HttpClient發(fā)起Get請(qǐng)求 public class DoGET { public static void main(String[] args) throws Exception { // 創(chuàng)建Httpclient對(duì)象,相當(dāng)于打開了瀏覽器 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創(chuàng)建HttpGet請(qǐng)求,相當(dāng)于在瀏覽器輸入地址 HttpGet httpGet = new HttpGet("http://www.baidu.com/"); CloseableHttpResponse response = null; try { // 執(zhí)行請(qǐng)求,相當(dāng)于敲完地址后按下回車。獲取響應(yīng) response = httpclient.execute(httpGet); // 判斷返回狀態(tài)是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應(yīng),獲取數(shù)據(jù) String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { // 關(guān)閉資源 response.close(); } // 關(guān)閉瀏覽器 httpclient.close(); } } } //2、使用HttpClient發(fā)起帶參數(shù)的Get請(qǐng)求 public class DoGETParam { public static void main(String[] args) throws Exception { // 創(chuàng)建Httpclient對(duì)象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創(chuàng)建URI對(duì)象,并且設(shè)置請(qǐng)求參數(shù) URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build(); // 創(chuàng)建http GET請(qǐng)求 HttpGet httpGet = new HttpGet(uri); // HttpGet get = new HttpGet("http://www.baidu.com/s?wd=java"); CloseableHttpResponse response = null; try { // 執(zhí)行請(qǐng)求 response = httpclient.execute(httpGet); // 判斷返回狀態(tài)是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應(yīng)數(shù)據(jù) String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } } //3、使用HttpClient發(fā)起POST請(qǐng)求 public class DoPOST { public static void main(String[] args) throws Exception { // 創(chuàng)建Httpclient對(duì)象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創(chuàng)建http POST請(qǐng)求 HttpPost httpPost = new HttpPost("http://www.oschina.net/"); // 把自己偽裝成瀏覽器。否則開源中國(guó)會(huì)攔截訪問 httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); CloseableHttpResponse response = null; try { // 執(zhí)行請(qǐng)求 response = httpclient.execute(httpPost); // 判斷返回狀態(tài)是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應(yīng)數(shù)據(jù) String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } // 關(guān)閉瀏覽器 httpclient.close(); } } } //4、使用HttpClient發(fā)起帶有參數(shù)的POST請(qǐng)求 public class DoPOSTParam { public static void main(String[] args) throws Exception { // 創(chuàng)建Httpclient對(duì)象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創(chuàng)建http POST請(qǐng)求,訪問開源中國(guó) HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); // 根據(jù)開源中國(guó)的請(qǐng)求需要,設(shè)置post請(qǐng)求參數(shù) List<NameValuePair> parameters = new ArrayList<NameValuePair>(0); parameters.add(new BasicNameValuePair("scope", "project")); parameters.add(new BasicNameValuePair("q", "java")); parameters.add(new BasicNameValuePair("fromerr", "8bDnUWwC")); // 構(gòu)造一個(gè)form表單式的實(shí)體 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); // 將請(qǐng)求實(shí)體設(shè)置到httpPost對(duì)象中 httpPost.setEntity(formEntity); CloseableHttpResponse response = null; try { // 執(zhí)行請(qǐng)求 response = httpclient.execute(httpPost); // 判斷返回狀態(tài)是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應(yīng)體 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } // 關(guān)閉瀏覽器 httpclient.close(); } } }
二、RestTemplate
RestTemplate是Spring提供的用于訪問Rest服務(wù)的客戶端,RestTemplate提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法
HTTP開發(fā)是用apache的HttpClient開發(fā),代碼復(fù)雜,還得操心資源回收等。代碼很復(fù)雜,冗余代碼多。
導(dǎo)入坐標(biāo)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
創(chuàng)建RestTemplate對(duì)象
@Configuration//加上這個(gè)注解作用,可以被Spring掃描 public class RestTemplateConfig { /** * 創(chuàng)建RestTemplate對(duì)象,將RestTemplate對(duì)象的生命周期的管理交給Spring * @return */ @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); //主要解決中文亂碼 restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); return restTemplate; } }
RestTempController
import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; @RestController @RequestMapping("/consumer") public class ConsumerController { // 從Spring的容器中獲取restTemplate @Resource private RestTemplate restTemplate; /** * 通過Get請(qǐng)求,保存數(shù)據(jù) */ @GetMapping("/{id}") public ResponseEntity<String> findById(@PathVariable Integer id){ //發(fā)起遠(yuǎn)程請(qǐng)求:通過RestTemplate發(fā)起get請(qǐng)求 ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8090/goods2/1", String.class); System.out.println("entity.getStatusCode():"+entity.getStatusCode()); System.out.println(entity.getBody()); return entity; } /** * 通過Post請(qǐng)求,保存數(shù)據(jù) */ @PostMapping public ResponseEntity<String> saveGoods(@RequestBody Goods goods){ //通過RestTemplate發(fā)起遠(yuǎn)程請(qǐng)求 /** * 第一個(gè)參數(shù):遠(yuǎn)程地址URI * 第二個(gè)參數(shù):數(shù)據(jù) * 第三個(gè)參數(shù):返回值類型 */ ResponseEntity<String> entity = restTemplate.postForEntity("http://localhost:8090/goods2", goods, String.class); System.out.println("entity.getStatusCode():"+entity.getStatusCode()); System.out.println(entity.getBody()); return entity; } @PutMapping public ResponseEntity<String> updateGoods(@RequestBody Goods goods){ restTemplate.put("http://localhost:8090/goods2",goods); return new ResponseEntity<>("修改成功", HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<String> deleteById(@PathVariable Integer id){ restTemplate.delete("http://localhost:8090/goods2/"+id); return new ResponseEntity<>("刪除成功", HttpStatus.OK); } }
只用maven不用springboot框架時(shí)只需要導(dǎo)入依賴到pom文件
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency>
直接new RestTemplate()對(duì)象使用即可
到此這篇關(guān)于Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法的文章就介紹到這了,更多相關(guān)Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot 如何使用RestTemplate來調(diào)用接口
- SpringBoot-RestTemplate如何實(shí)現(xiàn)調(diào)用第三方API
- Spring boot2X Consul如何通過RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用
- 關(guān)于SpringBoot大文件RestTemplate下載解決方案
- 基于springboot的RestTemplate、okhttp和HttpClient對(duì)比分析
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- RestTemplate接口調(diào)用神器常見用法匯總
- Springboot使用RestTemplate調(diào)用第三方接口的操作代碼
相關(guān)文章
詳解java倒計(jì)時(shí)三種簡(jiǎn)單實(shí)現(xiàn)方式
這篇文章主要介紹了詳解java倒計(jì)時(shí)三種簡(jiǎn)單實(shí)現(xiàn)方式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09jetbrain?fleet對(duì)標(biāo)vscode實(shí)際操作
Gradle是一個(gè)基于Apache Ant和Apache Maven概念項(xiàng)目自動(dòng)化構(gòu)建開源工具,jetbrain家的fleet(已獲得預(yù)覽權(quán)限)直接對(duì)標(biāo)vscode?,?fleet有望超過vscode嗎?今天我們實(shí)際操作下2021-12-12Java中如何取出String字符串括號(hào)中的內(nèi)容
這篇文章主要介紹了Java中如何取出String字符串括號(hào)中的內(nèi)容問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05Java多線程中ReentrantLock與Condition詳解
這篇文章主要介紹了Java多線程中ReentrantLock與Condition詳解,需要的朋友可以參考下2017-11-11mybatis框架order by作為參數(shù)傳入時(shí)失效的解決
這篇文章主要介紹了mybatis框架order by作為參數(shù)傳入時(shí)失效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Java編程synchronized與lock的區(qū)別【推薦】
互聯(lián)網(wǎng)信息泛濫環(huán)境下少有的良心之作!如果您想對(duì)Java編程synchronized與lock的區(qū)別有所了解,這篇文章絕對(duì)值得!分享給大家,供需要的朋友參考。不說了,我先學(xué)習(xí)去了。2017-10-10Spring Boot 項(xiàng)目啟動(dòng)失敗的解決方案
這篇文章主要介紹了Spring Boot 項(xiàng)目啟動(dòng)失敗的解決方案,幫助大家更好的理解和學(xué)習(xí)使用Spring Boot,感興趣的朋友可以了解下2021-03-03SpringMVC 文件上傳配置,多文件上傳,使用的MultipartFile的實(shí)例
本篇文章主要介紹了SpringMVC 文件上傳配置,詳解介紹了如何使用SpringMVC進(jìn)行表單上的文件上傳以及多個(gè)文件同時(shí)上傳的步驟,有興趣的可以了解一下。2016-12-12Java 靜態(tài)綁定與動(dòng)態(tài)綁定深入分析
這篇文章主要介紹了Java 靜態(tài)綁定與動(dòng)態(tài)綁定深入分析的相關(guān)資料,這里對(duì)java 的動(dòng)態(tài)綁定和靜態(tài)綁定做了詳細(xì)的介紹,對(duì)其進(jìn)行總結(jié)整理,需要的朋友可以參考下2016-11-11Spring boot創(chuàng)建自定義starter的完整步驟
這篇文章主要給大家介紹了關(guān)于Spring boot創(chuàng)建自定義starter的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09