最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法

 更新時(shí)間:2021年03月06日 12:13:51   作者:依舊ฅ=ฅ  
這篇文章主要介紹了Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、HttpClient

兩個(gè)系統(tǒng)間如何互相訪問(wèn)??jī)蓚€(gè)tomcat上的項(xiàng)目如何互相訪問(wèn)?

       采用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)于打開(kāi)了瀏覽器
    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/");
    // 把自己偽裝成瀏覽器。否則開(kāi)源中國(guó)會(huì)攔截訪問(wèn)
    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)求,訪問(wèn)開(kāi)源中國(guó)
    HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
 
    // 根據(jù)開(kāi)源中國(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提供的用于訪問(wèn)Rest服務(wù)的客戶端,RestTemplate提供了多種便捷訪問(wèn)遠(yuǎn)程Http服務(wù)的方法

HTTP開(kāi)發(fā)是用apache的HttpClient開(kāi)發(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;
 
  /**
   * 通過(guò)Get請(qǐng)求,保存數(shù)據(jù)
   */
  @GetMapping("/{id}")
  public ResponseEntity<String> findById(@PathVariable Integer id){
    //發(fā)起遠(yuǎn)程請(qǐng)求:通過(guò)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;
  }
 
  /**
   * 通過(guò)Post請(qǐng)求,保存數(shù)據(jù)
   */
  @PostMapping
  public ResponseEntity<String> saveGoods(@RequestBody Goods goods){
    //通過(guò)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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談Mybatis獲取參數(shù)值的方式

    淺談Mybatis獲取參數(shù)值的方式

    本文主要介紹了Mybatis獲取參數(shù)值的方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • postman中POST請(qǐng)求時(shí)參數(shù)包含參數(shù)list設(shè)置方式

    postman中POST請(qǐng)求時(shí)參數(shù)包含參數(shù)list設(shè)置方式

    這篇文章主要介紹了postman中POST請(qǐng)求時(shí)參數(shù)包含參數(shù)list設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-05-05
  • Java?8函數(shù)式接口之BinaryOperator使用示例詳解

    Java?8函數(shù)式接口之BinaryOperator使用示例詳解

    這篇文章主要大家介紹了Java?8函數(shù)式接口之BinaryOperator,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • Java中打jar包以及如何調(diào)用包方法演示

    Java中打jar包以及如何調(diào)用包方法演示

    這篇文章主要給大家介紹了關(guān)于Java中打jar包以及如何調(diào)用包的相關(guān)資料,jar包的全稱是java archive,jar包本質(zhì)就是一種壓縮包,在Java開(kāi)發(fā)中一般是用來(lái)壓縮類的一個(gè)包,需要的朋友可以參考下
    2023-09-09
  • PowerJob的DatabaseMonitorAspect源碼流程

    PowerJob的DatabaseMonitorAspect源碼流程

    這篇文章主要為大家介紹了PowerJob的DatabaseMonitorAspect源碼流程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Java中JSONObject和Map<String,?Object>的轉(zhuǎn)換方法

    Java中JSONObject和Map<String,?Object>的轉(zhuǎn)換方法

    平時(shí)對(duì)接口時(shí),經(jīng)常遇到j(luò)son字符串和map對(duì)象之間的交互,這篇文章主要給大家介紹了關(guān)于Java中JSONObject和Map<String,?Object>的轉(zhuǎn)換方法,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-07-07
  • 新版SpringSecurity5.x使用與配置詳解

    新版SpringSecurity5.x使用與配置詳解

    Spring Security是一個(gè)強(qiáng)大且高度可定制的身份驗(yàn)證和訪問(wèn)控制框架,本文主要介紹了新版SpringSecurity5.x使用與配置詳解,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-08-08
  • java的多線程用法編程總結(jié)

    java的多線程用法編程總結(jié)

    本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等。
    2016-10-10
  • 解決fastjson泛型轉(zhuǎn)換報(bào)錯(cuò)的解決方法

    解決fastjson泛型轉(zhuǎn)換報(bào)錯(cuò)的解決方法

    這篇文章主要介紹了解決fastjson泛型轉(zhuǎn)換報(bào)錯(cuò)的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Spring Boot中的SpringSecurity基礎(chǔ)教程

    Spring Boot中的SpringSecurity基礎(chǔ)教程

    Spring Security是一個(gè)功能強(qiáng)大且高度可定制的身份驗(yàn)證和訪問(wèn)控制框架。它實(shí)際上是保護(hù)基于spring的應(yīng)用程序的標(biāo)準(zhǔn)Spring Security是一個(gè)框架,側(cè)重于為Java應(yīng)用程序提供身份驗(yàn)證和授權(quán),這篇文章主要介紹了Spring Boot中的SpringSecurity學(xué)習(xí),需要的朋友可以參考下
    2023-01-01

最新評(píng)論

永仁县| 花垣县| 遂平县| 偏关县| 永新县| 黄平县| 长汀县| 金坛市| 赤壁市| 蒙阴县| 马公市| 九江市| 临朐县| 中阳县| 遂宁市| 保康县| 兴城市| 江华| 榆社县| 太谷县| 昆明市| 安平县| 平和县| 富顺县| 孟村| 长宁区| 武义县| 富源县| 东兴市| 丘北县| 和顺县| 安新县| 土默特右旗| 阿克| 青浦区| 定南县| 富川| 麦盖提县| 宁强县| 手游| 湾仔区|