<ruby id="cibvo"></ruby>
<ruby id="cibvo"></ruby>
<strong id="cibvo"></strong>

      <ruby id="cibvo"><table id="cibvo"></table></ruby>

    1. <strong id="cibvo"></strong>
    2. <strong id="cibvo"></strong>

      SpringBoot 調用外部接口的三種方式 世界短訊

      來源:架構師社區時間:2023-04-26 19:12:42

      作者:Chelsea


      【資料圖】

      來源:blog.csdn.net/Chelsea__/article/details/126689495

      1、簡介

      SpringBoot不僅繼承了Spring框架原有的優秀特性,而且還通過簡化配置來進一步簡化了Spring應用的整個搭建和開發過程。在Spring-Boot項目開發中,存在著本模塊的代碼需要訪問外面模塊接口,或外部url鏈接的需求, 比如在apaas開發過程中需要封裝接口在接口中調用apaas提供的接口(像發起流程接口submit等等)下面也是提供了三種方式(不使用dubbo的方式)供我們選擇

      2、方式一:使用原始httpClient請求

      /**@descriptionget方式獲取入參,插入數據并發起流程*@authorlyx*@date2022/8/2416:05*@paramsdocumentId*@returnString*///@RequestMapping(\"/submit/{documentId}\")publicStringsubmit1(@PathVariableStringdocumentId)throwsParseException{//此處將要發送的數據轉換為json格式字符串Mapmap=task2Service.getMap(documentId);StringjsonStr=JSON.toJSONString(map,SerializerFeature.WRITE_MAP_NULL_FEATURES,SerializerFeature.QuoteFieldNames);JSONObjectjsonObject=JSON.parseObject(jsonStr);JSONObjectsr=task2Service.doPost(jsonObject);returnsr.toString();}

      /**@description使用原生httpClient調用外部接口*@authorlyx*@date2022/8/2416:08*@paramsdate*@returnJSONObject*/publicstaticJSONObjectdoPost(JSONObjectdate){StringassessToken=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ\";CloseableHttpClientclient=HttpClients.createDefault();//要調用的接口urlStringurl=\"http://39.103.201.110:30661/xdap-open/open/process/v1/submit\";HttpPostpost=newHttpPost(url);JSONObjectjsonObject=null;try{//創建請求體并添加數據StringEntitys=newStringEntity(date.toString());//此處相當于在header里頭添加content-type等參數s.setContentType(\"application/json\");s.setContentEncoding(\"UTF-8\");post.setEntity(s);//此處相當于在Authorization里頭添加Beartoken參數信息post.addHeader(\"Authorization\",\"Bearer\"+assessToken);HttpResponseres=client.execute(post);Stringresponse1=EntityUtils.toString(res.getEntity());if(res.getStatusLine().getStatusCode()==HttpStatus.SC_OK){//返回json格式:Stringresult=EntityUtils.toString(res.getEntity());jsonObject=JSONObject.parseObject(result);}}catch(Exceptione){thrownewRuntimeException(e);}returnjsonObject;}

      3、方式二:使用RestTemplate方法

      Spring-Boot開發中,RestTemplate同樣提供了對外訪問的接口API,這里主要介紹Get和Post方法的使用。

      Get請求

      提供了getForObject、getForEntity兩種方式,其中getForEntity如下三種方法的實現:

      Get--getForEntity,存在以下兩種方式重載

      1.getForEntity(Stringurl,ClassresponseType,Object…urlVariables)2.getForEntity(URIurl,ClassresponseType)

      Get--getForEntity(URI url,Class responseType)

      //該方法使用URI對象來替代之前的url和urlVariables參數來指定訪問地址和參數綁定。URI是JDK java.net包下的一個類,表示一個統一資源標識符(Uniform Resource Identifier)引用。參考如下:RestTemplaterestTemplate=newRestTemplate();UriComponentsuriComponents=UriComponentsBuilder.fromUriString(\"http://USER-SERVICE/user?name={name}\").build().expand(\"dodo\").encode();URIuri=uriComponents.toUri();ResponseEntityresponseEntity=restTemplate.getForEntity(uri,String.class).getBody();

      Get--getForEntity(Stringurl,Class responseType,Object…urlVariables)

      //該方法提供了三個參數,其中url為請求的地址,responseType為請求響應body的包裝類型,urlVariables為url中的參數綁定,該方法的參考調用如下://http://USER-SERVICE/user?name={name)RestTemplaterestTemplate=newRestTemplate();Mapparams=newHashMap<>();params.put(\"name\",\"dada\");//ResponseEntityresponseEntity=restTemplate.getForEntity(\"http://USERSERVICE/user?name={name}\",String.class,params);

      Get--getForObject,存在以下三種方式重載

      1.getForObject(Stringurl,ClassresponseType,Object...urlVariables)2.getForObject(Stringurl,ClassresponseType,MapurlVariables)3.getForObject(URIurl,ClassresponseType)

      getForObject方法可以理解為對getForEntity的進一步封裝,它通過HttpMessageConverterExtractor對HTTP的請求響應體body內容進行對象轉換,實現請求直接返回包裝好的對象內容。

      Post 請求

      Post請求提供有postForEntity、postForObjectpostForLocation三種方式,其中每種方式都有三種方法,下面介紹postForEntity的使用方法。

      Post--postForEntity,存在以下三種方式重載

      1.postForEntity(Stringurl,Objectrequest,ClassresponseType,Object...uriVariables)2.postForEntity(Stringurl,Objectrequest,ClassresponseType,MapuriVariables)3.postForEntity(URIurl,Objectrequest,ClassresponseType)

      如下僅演示第二種重載方式

      /**@descriptionpost方式獲取入參,插入數據并發起流程*@authorlyx*@date2022/8/2416:07*@params*@return*/@PostMapping(\"/submit2\")publicObjectinsertFinanceCompensation(@RequestBodyJSONObjectjsonObject){StringdocumentId=jsonObject.get(\"documentId\").toString();returntask2Service.submit(documentId);}
      /**@description使用restTimeplate調外部接口*@authorlyx*@date2022/8/2416:02*@paramsdocumentId*@returnString*/publicStringsubmit(StringdocumentId){StringassessToken=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ\";RestTemplaterestTemplate=newRestTemplate();//創建請求頭HttpHeadershttpHeaders=newHttpHeaders();//此處相當于在Authorization里頭添加Beartoken參數信息httpHeaders.add(HttpHeaders.AUTHORIZATION,\"Bearer\"+assessToken);//此處相當于在header里頭添加content-type等參數httpHeaders.add(HttpHeaders.CONTENT_TYPE,\"application/json\");Mapmap=getMap(documentId);StringjsonStr=JSON.toJSONString(map);//創建請求體并添加數據HttpEntityhttpEntity=newHttpEntity(map,httpHeaders);Stringurl=\"http://39.103.201.110:30661/xdap-open/open/process/v1/submit\";ResponseEntityforEntity=restTemplate.postForEntity(url,httpEntity,String.class);//此處三個參數分別是請求地址、請求體以及返回參數類型returnforEntity.toString();}

      4、方式三:使用Feign進行消費

      在maven項目中添加依賴

      org.springframework.cloudspring-cloud-starter-feign1.2.2.RELEASE

      啟動類上加上@EnableFeignClients

      @SpringBootApplication@EnableFeignClients@ComponentScan(basePackages={\"com.definesys.mpaas\",\"com.xdap.*\",\"com.xdap.*\"})publicclassMobilecardApplication{publicstaticvoidmain(String[]args){SpringApplication.run(MobilecardApplication.class,args);}}

      此處編寫接口模擬外部接口供feign調用外部接口方式使用

      定義controller

      @AutowiredPrintServiceprintService;@PostMapping(\"/outSide\")publicStringtest(@RequestBodyTestDtotestDto){returnprintService.print(testDto);}

      定義service

      @ServicepublicinterfacePrintService{publicStringprint(TestDtotestDto);}

      定義serviceImpl

      publicclassPrintServiceImplimplementsPrintService{@OverridepublicStringprint(TestDtotestDto){return\"模擬外部系統的接口功能\"+testDto.getId();}}

      構建Feigin的Service

      定義service

      //此處name需要設置不為空,url需要在.properties中設置@Service@FeignClient(url=\"${outSide.url}\",name=\"service2\")publicinterfaceFeignService2{@RequestMapping(value=\"/custom/outSide\",method=RequestMethod.POST)@ResponseBodypublicStringgetMessage(@Valid@RequestBodyTestDtotestDto);}

      定義controller

      @AutowiredFeignService2feignService2;//測試feign調用外部接口入口@PostMapping(\"/test2\")publicStringtest2(@RequestBodyTestDtotestDto){returnfeignService2.getMessage(testDto);}

      postman測試

      此處因為我使用了所在項目,所以需要添加一定的請求頭等信息,關于Feign的請求頭添加也會在后續補充

      補充如下:

      添加Header解決方法

      將token等信息放入Feign請求頭中,主要通過重寫RequestInterceptor的apply方法實現

      定義config

      @ConfigurationpublicclassFeignConfigimplementsRequestInterceptor{@Overridepublicvoidapply(RequestTemplaterequestTemplate){//添加tokenrequestTemplate.header(\"token\",\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ\");}}

      定義service

      @Service@FeignClient(url=\"${outSide.url}\",name=\"feignServer\",configuration=FeignDemoConfig.class)publicinterfaceTokenDemoClient{@RequestMapping(value=\"/custom/outSideAddToken\",method=RequestMethod.POST)@ResponseBodypublicStringgetMessage(@Valid@RequestBodyTestDtotestDto);}

      定義controller

      //測試feign調用外部接口入口,加上token@PostMapping(\"/testToken\")publicStringtest4(@RequestBodyTestDtotestDto){returntokenDemoClient.getMessage(testDto);}

      標簽:

      責任編輯:FD31
      上一篇:河南:鄭州高新區獲批國家海外人才離岸創新創業基地|最新
      下一篇:即時焦點:一季度金融支持天津市重點建設項目取得新成效

      精彩圖集(熱圖)

      最近更新

      信用中國

      • 信用信息
      • 行政許可和行政處罰
      • 網站文章

      91在线无码精品秘 入口九_性色aV一区二区三区咪爱_亚洲mv国产mv在线mv综合_五月丁香色综合久久4438
      <ruby id="cibvo"></ruby>
      <ruby id="cibvo"></ruby>
      <strong id="cibvo"></strong>

          <ruby id="cibvo"><table id="cibvo"></table></ruby>

        1. <strong id="cibvo"></strong>
        2. <strong id="cibvo"></strong>