欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring-Boot 訪問外部接口的方案總結

 更新時間:2022年12月05日 10:30:26   作者:polo2044  
在Spring-Boot項目開發(fā)中,存在著本模塊的代碼需要訪問外面模塊接口,或外部url鏈接的需求,針對這一需求目前存在著三種解決方案,下面將對這三種方案進行整理和說明,對Spring-Boot 訪問外部接口方案感興趣的朋友跟隨小編一起看看吧

一、簡介

在Spring-Boot項目開發(fā)中,存在著本模塊的代碼需要訪問外面模塊接口,或外部url鏈接的需求,針對這一需求目前存在著三種解決方案,下面將對這三種方案進行整理和說明。

二、Spring-Boot項目中訪問外部接口

2.1 方案一 采用原生的Http請求

在代碼中采用原生的http請求,代碼參考如下:

@RequestMapping("/doPostGetJson")
public String doPostGetJson() throws ParseException {
   //此處將要發(fā)送的數(shù)據(jù)轉換為json格式字符串
   String jsonText = "{id:1}";
   JSONObject json = (JSONObject) JSONObject.parse(jsonText);
   JSONObject sr = this.doPost(json);
   System.out.println("返回參數(shù):" + sr);
   return sr.toString();
}

public static JSONObject doPost(JSONObject date) {
   HttpClient client = HttpClients.createDefault();
   // 要調用的接口方法
   String url = "http://192.168.1.101:8080/getJson";
   HttpPost post = new HttpPost(url);
   JSONObject jsonObject = null;
   try {
      StringEntity s = new StringEntity(date.toString());
      s.setContentEncoding("UTF-8");
      s.setContentType("application/json");
      post.setEntity(s);
      post.addHeader("content-type", "text/xml");
      HttpResponse res = client.execute(post);
      String response1 = EntityUtils.toString(res.getEntity());
      System.out.println(response1);
      if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
         String result = EntityUtils.toString(res.getEntity());// 返回json格式:
         jsonObject = JSONObject.parseObject(result);
      }
   } catch (Exception e) {
      throw new RuntimeException(e);
   }
   return jsonObject;
}

2.2 方案二 采用Feign進行消費

1、在maven項目中添加依賴

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-feign</artifactId>
      <version>1.2.2.RELEASE</version>
</dependency>

2、編寫接口,放置在service層

@FeignClient(url = "${decisionEngine.url}",name="engine")
public interface DecisionEngineService {
  @RequestMapping(value="/decision/person",method= RequestMethod.POST)
  public JSONObject getEngineMesasge(@RequestParam("uid") String uid,@RequestParam("productCode") String productCode);

}

這里的decisionEngine.url 是配置在properties中的 是ip地址和端口號
decisionEngine.url=http://10.2.1.148:3333
/decision/person 是接口名字

3、在Java的啟動類上加上@EnableFeignClients

@EnableFeignClients //參見此處
@EnableDiscoveryClient
@SpringBootApplication
@EnableResourceServer
public class Application   implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
    @Autowired
    private AppMetricsExporter appMetricsExporter;

    @Autowired
    private AddMonitorUnitService addMonitorUnitService;

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }    
}

4、在代碼中調用接口即可

@Autowired
    private DecisionEngineService decisionEngineService ;
    decisionEngineService.getEngineMesasge("uid" ,  "productCode");

2.3、方案三 采用RestTemplate方法

在Spring-Boot開發(fā)中,RestTemplate同樣提供了對外訪問的接口API,這里主要介紹Get和Post方法的使用。Get請求提供了兩種方式的接口getForObject 和 getForEntity,getForEntity提供如下三種方法的實現(xiàn)。
Get請求之——getForEntity(Stringurl,Class responseType,Object…urlVariables)
該方法提供了三個參數(shù),其中url為請求的地址,responseType為請求響應body的包裝類型,urlVariables為url中的參數(shù)綁定,該方法的參考調用如下:

//http://USER-SERVICE/user?name={1}
getForEntity("http://USER-SERVICE/user?name={1}",String.class,"didi")

Get請求之——getForEntity(String url,Class responseType,Map urlVariables)
該方法提供的參數(shù)中urlVariables的參數(shù)類型使用了Map類型,因此在使用該方法進行參數(shù)綁定時需要在占位符中指定Map中參數(shù)的key值,該方法的參考調用如下:

// http://USER-SERVICE/user?name={name)
RestTemplate restTemplate=new RestTemplate();
Map<String,String> params=new HashMap<>();
params.put("name","dada");  //
ResponseEntity<String> responseEntity=restTemplate.getForEntity("http://USERSERVICE/user?name={name}",String.class,params);

Get請求之——getForEntity(URI url,Class responseType)
該方法使用URI對象來替代之前的url和urlVariables參數(shù)來指定訪問地址和參數(shù)綁定。URI是JDK java.net包下的一個類,表示一個統(tǒng)一資源標識符(Uniform Resource Identifier)引用。參考如下:

RestTemplate restTemplate=new RestTemplate();
UriComponents uriComponents=UriComponentsBuilder.fromUriString(
"http://USER-SERVICE/user?name={name}")
.build()
.expand("dodo")
.encode();
URI uri=uriComponents.toUri();
ResponseEntity<String> responseEntity=restTemplate.getForEntity(uri,String.class).getBody();

Get請求之——getForObject
getForObject方法可以理解為對getForEntity的進一步封裝,它通過HttpMessageConverterExtractor對HTTP的請求響應體body內容進行對象轉換,實現(xiàn)請求直接返回包裝好的對象內容。getForObject方法有如下:

getForObject(String url,Class responseType,Object...urlVariables)
getForObject(String url,Class responseType,Map urlVariables)
getForObject(URI url,Class responseType)

Post請求提供有三種方法,postForEntity、postForObject和postForLocation。其中每種方法都存在三種方法,postForEntity方法使用如下:

RestTemplate restTemplate=new RestTemplate();
User user=newUser("didi",30);
ResponseEntity<String> responseEntity=restTemplate.postForEntity("http://USER-SERVICE/user",user,String.class); //提交的body內容為user對象,請求的返回的body類型為String
String body=responseEntity.getBody();

postForEntity存在如下三種方法的重載

postForEntity(String url,Object request,Class responseType,Object... uriVariables)
postForEntity(String url,Object request,Class responseType,Map uriVariables)
postForEntity(URI url,Object request,Class responseType)

postForEntity中的其它參數(shù)和getForEntity的參數(shù)大體相同在此不做介紹。

參考文獻

1.淺析SpringBoot微服務中異步調用數(shù)據(jù)提交數(shù)據(jù)庫的問題
2.spring boot 常見http請求url參數(shù)獲取方法
3.Spring學習筆記之RestTemplate使用小結
4.Spring RestTemplate中幾種常見的請求方式
5.Springboot使用RestTemplate調用第三方接口的操作代碼

到此這篇關于Spring-Boot 訪問外部接口的方案總結的文章就介紹到這了,更多相關Spring-Boot 訪問外部接內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Springboot插件開發(fā)實戰(zhàn)分享

    Springboot插件開發(fā)實戰(zhàn)分享

    這篇文章主要介紹了Springboot插件開發(fā)實戰(zhàn)分享,文章通過新建aop切面執(zhí)行類MonitorLogInterceptor展開詳細的相關內容,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • Java實現(xiàn)選擇排序算法的實例教程

    Java實現(xiàn)選擇排序算法的實例教程

    這篇文章主要介紹了Java實現(xiàn)選擇排序算法的實例教程,選擇排序的時間復雜度為О(n&sup2;),需要的朋友可以參考下
    2016-05-05
  • Spring整合Redis完整實例代碼

    Spring整合Redis完整實例代碼

    這篇文章主要介紹了Spring整合Redis完整實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • mybatis空值插入處理的解決方法

    mybatis空值插入處理的解決方法

    本文主要介紹了mybatis空值插入處理的解決方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • spring boot中使用http請求的示例代碼

    spring boot中使用http請求的示例代碼

    本篇文章主要介紹了spring boot中 使用http請求的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • java substring 截取字符串的方法

    java substring 截取字符串的方法

    這篇文章主要介紹了java substring 截取字符串的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-05-05
  • Spring AOP 與代理的概念與使用

    Spring AOP 與代理的概念與使用

    大家知道我現(xiàn)在還是一個 CRUD 崽,平時用 AOP 也是 CV 大法。最近痛定思痛,決定研究一下 Spring AOP 的原理。 這里寫一篇文章總結一下。主要介紹 Java 中 AOP 的實現(xiàn)原理,最后以兩個簡單的示例來收尾。
    2020-10-10
  • RocketMQ根據(jù)Tag進行消息過濾

    RocketMQ根據(jù)Tag進行消息過濾

    消費者訂閱了某個主題后,Apache RocketMQ 會將該主題中的所有消息投遞給消費者。若消費者只需要關注部分消息,可通過設置過濾條件在 Apache RocketMQ 服務端進行過濾,只獲取到需要關注的消息子集,避免接收到大量無效的消息
    2023-02-02
  • 詳解如何使用Java流API構建樹形結構數(shù)據(jù)

    詳解如何使用Java流API構建樹形結構數(shù)據(jù)

    在實際開發(fā)中,構建樹狀層次結構是常見需求,本文主要為大家詳細介紹了如何使用Java 8 Stream API將扁平化的菜單數(shù)據(jù)轉換為具有層級關系的樹形結構,需要的可以參考下
    2024-04-04
  • Java中easypoi導入excel文件列名相同的處理方案

    Java中easypoi導入excel文件列名相同的處理方案

    這篇文章主要介紹了Java中easypoi導入excel文件列名相同的處理方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06

最新評論