国产乱人伦偷精品视频不卡_久久久国产综合精品女国产盗摄_亚洲精品视频在线_一本一道波多野结衣一区二区

SpringBoot 調(diào)用外部接口的三種方式 世界短訊

來(lái)源:架構(gòu)師社區(qū)時(shí)間:2023-04-26 19:12:42

作者:Chelsea


【資料圖】

來(lái)源:blog.csdn.net/Chelsea__/article/details/126689495

1、簡(jiǎn)介

SpringBoot不僅繼承了Spring框架原有的優(yōu)秀特性,而且還通過(guò)簡(jiǎn)化配置來(lái)進(jìn)一步簡(jiǎn)化了Spring應(yīng)用的整個(gè)搭建和開(kāi)發(fā)過(guò)程。在Spring-Boot項(xiàng)目開(kāi)發(fā)中,存在著本模塊的代碼需要訪問(wèn)外面模塊接口,或外部url鏈接的需求, 比如在apaas開(kāi)發(fā)過(guò)程中需要封裝接口在接口中調(diào)用apaas提供的接口(像發(fā)起流程接口submit等等)下面也是提供了三種方式(不使用dubbo的方式)供我們選擇

2、方式一:使用原始httpClient請(qǐng)求

/**@descriptionget方式獲取入?yún)ⅲ迦霐?shù)據(jù)并發(fā)起流程*@authorlyx*@date2022/8/2416:05*@paramsdocumentId*@returnString*///@RequestMapping(\"/submit/{documentId}\")publicStringsubmit1(@PathVariableStringdocumentId)throwsParseException{//此處將要發(fā)送的數(shù)據(jù)轉(zhuǎn)換為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調(diào)用外部接口*@authorlyx*@date2022/8/2416:08*@paramsdate*@returnJSONObject*/publicstaticJSONObjectdoPost(JSONObjectdate){StringassessToken=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ\";CloseableHttpClientclient=HttpClients.createDefault();//要調(diào)用的接口urlStringurl=\"http://39.103.201.110:30661/xdap-open/open/process/v1/submit\";HttpPostpost=newHttpPost(url);JSONObjectjsonObject=null;try{//創(chuàng)建請(qǐng)求體并添加數(shù)據(jù)StringEntitys=newStringEntity(date.toString());//此處相當(dāng)于在header里頭添加content-type等參數(shù)s.setContentType(\"application/json\");s.setContentEncoding(\"UTF-8\");post.setEntity(s);//此處相當(dāng)于在Authorization里頭添加Beartoken參數(shù)信息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開(kāi)發(fā)中,RestTemplate同樣提供了對(duì)外訪問(wèn)的接口API,這里主要介紹Get和Post方法的使用。

Get請(qǐng)求

提供了getForObjectgetForEntity兩種方式,其中getForEntity如下三種方法的實(shí)現(xiàn):

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

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

Get--getForEntity(URI url,Class responseType)

//該方法使用URI對(duì)象來(lái)替代之前的url和urlVariables參數(shù)來(lái)指定訪問(wèn)地址和參數(shù)綁定。URI是JDK java.net包下的一個(gè)類(lèi),表示一個(gè)統(tǒng)一資源標(biāo)識(shí)符(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)

//該方法提供了三個(gè)參數(shù),其中url為請(qǐng)求的地址,responseType為請(qǐng)求響應(yīng)body的包裝類(lèi)型,urlVariables為url中的參數(shù)綁定,該方法的參考調(diào)用如下://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方法可以理解為對(duì)getForEntity的進(jìn)一步封裝,它通過(guò)HttpMessageConverterExtractor對(duì)HTTP的請(qǐng)求響應(yīng)體body內(nèi)容進(jìn)行對(duì)象轉(zhuǎn)換,實(shí)現(xiàn)請(qǐng)求直接返回包裝好的對(duì)象內(nèi)容。

Post 請(qǐng)求

Post請(qǐng)求提供有postForEntitypostForObjectpostForLocation三種方式,其中每種方式都有三種方法,下面介紹postForEntity的使用方法。

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

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

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

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

4、方式三:使用Feign進(jìn)行消費(fèi)

在maven項(xiàng)目中添加依賴(lài)

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

啟動(dòng)類(lèi)上加上@EnableFeignClients

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

此處編寫(xiě)接口模擬外部接口供feign調(diào)用外部接口方式使用

定義controller

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

定義service

@ServicepublicinterfacePrintService{publicStringprint(TestDtotestDto);}

定義serviceImpl

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

構(gòu)建Feigin的Service

定義service

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

定義controller

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

postman測(cè)試

此處因?yàn)槲沂褂昧怂陧?xiàng)目,所以需要添加一定的請(qǐng)求頭等信息,關(guān)于Feign的請(qǐng)求頭添加也會(huì)在后續(xù)補(bǔ)充

補(bǔ)充如下:

添加Header解決方法

將token等信息放入Feign請(qǐng)求頭中,主要通過(guò)重寫(xiě)RequestInterceptor的apply方法實(shí)現(xiàn)

定義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

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

標(biāo)簽:

責(zé)任編輯:FD31
上一篇:河南:鄭州高新區(qū)獲批國(guó)家海外人才離岸創(chuàng)新創(chuàng)業(yè)基地|最新
下一篇:即時(shí)焦點(diǎn):一季度金融支持天津市重點(diǎn)建設(shè)項(xiàng)目取得新成效

精彩圖集(熱圖)

熱點(diǎn)圖集

最近更新

信用中國(guó)

  • 信用信息
  • 行政許可和行政處罰
  • 網(wǎng)站文章

主站蜘蛛池模板: 久久免费一级片| 视频在线一区二区| 91成人国产在线观看| 国产精品国产精品国产专区不卡| 国产精品一区二区不卡视频| 韩国一区二区av| 国产欧美在线观看| 欧美成在线观看| 91精品91久久久久久| 日韩精品无码一区二区三区免费| 国产精品久久久久久久久免费看 | 国产精品美女诱惑| 在线视频不卡一区二区| 日本不卡一区二区三区视频| 欧美精品中文字幕一区二区| 国产免费亚洲高清| 日韩在线视频一区| 久久九九精品99国产精品| 国产精品美女诱惑| 亚洲中文字幕无码av永久| 青青草精品视频在线| 国产区日韩欧美| 日本午夜在线亚洲.国产| 国产精品三级网站| 欧美一区三区二区在线观看| 国产精品黄色av| 精品久久久91| 麻豆成人av| 日韩亚洲在线观看| www.久久草| 国产精品欧美风情| 久久精品色欧美aⅴ一区二区| 婷婷久久伊人| 91精品国产精品| 国产日韩在线一区二区三区| 日韩欧美视频网站| 69av视频在线播放| 91精品中文在线| 国产精品久久久久久婷婷天堂 | 国产精品10p综合二区| 久久久中文字幕|