Spring遠程調用HttpClient/RestTemplate的方法
一、HttpClient
兩個系統間如何互相訪問?兩個tomcat上的項目如何互相訪問?
采用HttpClient實現跨系統的接口調用。
介紹:
官網:http://hc.apache.org/index.html
現在也叫:HttpComponents
HttpClient可以發送get、post、put、delete、…等請求
使用:
導入坐標
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency>
//1、使用HttpClient發起Get請求 public class DoGET { public static void main(String[] args) throws Exception { // 創建Httpclient對象,相當於打開瞭瀏覽器 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建HttpGet請求,相當於在瀏覽器輸入地址 HttpGet httpGet = new HttpGet("http://www.baidu.com/"); CloseableHttpResponse response = null; try { // 執行請求,相當於敲完地址後按下回車。獲取響應 response = httpclient.execute(httpGet); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應,獲取數據 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { // 關閉資源 response.close(); } // 關閉瀏覽器 httpclient.close(); } } } //2、使用HttpClient發起帶參數的Get請求 public class DoGETParam { public static void main(String[] args) throws Exception { // 創建Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建URI對象,並且設置請求參數 URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build(); // 創建http GET請求 HttpGet httpGet = new HttpGet(uri); // HttpGet get = new HttpGet("http://www.baidu.com/s?wd=java"); CloseableHttpResponse response = null; try { // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應數據 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } } //3、使用HttpClient發起POST請求 public class DoPOST { public static void main(String[] args) throws Exception { // 創建Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建http POST請求 HttpPost httpPost = new HttpPost("http://www.oschina.net/"); // 把自己偽裝成瀏覽器。否則開源中國會攔截訪問 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 { // 執行請求 response = httpclient.execute(httpPost); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應數據 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } // 關閉瀏覽器 httpclient.close(); } } } //4、使用HttpClient發起帶有參數的POST請求 public class DoPOSTParam { public static void main(String[] args) throws Exception { // 創建Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 創建http POST請求,訪問開源中國 HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); // 根據開源中國的請求需要,設置post請求參數 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")); // 構造一個form表單式的實體 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); // 將請求實體設置到httpPost對象中 httpPost.setEntity(formEntity); CloseableHttpResponse response = null; try { // 執行請求 response = httpclient.execute(httpPost); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { // 解析響應體 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } // 關閉瀏覽器 httpclient.close(); } } }
二、RestTemplate
RestTemplate是Spring提供的用於訪問Rest服務的客戶端,RestTemplate提供瞭多種便捷訪問遠程Http服務的方法
HTTP開發是用apache的HttpClient開發,代碼復雜,還得操心資源回收等。代碼很復雜,冗餘代碼多。
導入坐標
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
創建RestTemplate對象
@Configuration//加上這個註解作用,可以被Spring掃描 public class RestTemplateConfig { /** * 創建RestTemplate對象,將RestTemplate對象的生命周期的管理交給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請求,保存數據 */ @GetMapping("/{id}") public ResponseEntity<String> findById(@PathVariable Integer id){ //發起遠程請求:通過RestTemplate發起get請求 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請求,保存數據 */ @PostMapping public ResponseEntity<String> saveGoods(@RequestBody Goods goods){ //通過RestTemplate發起遠程請求 /** * 第一個參數:遠程地址URI * 第二個參數:數據 * 第三個參數:返回值類型 */ 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框架時隻需要導入依賴到pom文件
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency>
直接new RestTemplate()對象使用即可
到此這篇關於Spring遠程調用HttpClient/RestTemplate的方法的文章就介紹到這瞭,更多相關Spring遠程調用HttpClient/RestTemplate內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBoot 接口開發教程(httpclient客戶端)
- Java基於HttpClient實現RPC的示例
- Java使用HttpClient詳細示例
- Java利用httpclient通過get、post方式調用https接口的方法
- spring集成httpclient配置的詳細過程