Spring-Boot项目开发中调用apaas接口的三种方式

1、简介
springboot不仅继承了spring框架原有的优秀特性,而且还通过简化配置来进一步简化了spring应用的整个搭建和开发过程。在spring-boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求, 比如在apaas开发过程中需要封装接口在接口中调用apaas提供的接口(像发起流程接口submit等等)下面也是提供了三种方式(不使用dubbo的方式)供我们选择
2、方式一:使用原始httpclient请求
/* * @description get方式获取入参,插入数据并发起流程 * @author lyx * @date 2022/8/24 16:05 * @params documentid * @return string *///@requestmapping(/submit/{documentid})public string submit1(@pathvariable string documentid) throws parseexception {    //此处将要发送的数据转换为json格式字符串    map map =task2service.getmap(documentid);    string jsonstr = json.tojsonstring(map, serializerfeature.write_map_null_features,serializerfeature.quotefieldnames);    jsonobject jsonobject = json.parseobject(jsonstr);    jsonobject sr = task2service.dopost(jsonobject);    return sr.tostring();}/* * @description 使用原生httpclient调用外部接口 * @author lyx * @date 2022/8/24 16:08 * @params date * @return jsonobject */public static jsonobject dopost(jsonobject date) {    string assesstoken=eyj0exaioijkv1qilcjhbgcioijiuzuxmij9.eyj4zgfwyxbwawqioiizndgxmju4odk2oti2oty1nzyilcjlehaioje2njeymjy5mdgsimlhdci6mty2mtixotcwocwiegrhchrlbmfudglkijoimzawotgxnja1mte0mduynja5iiwiegrhchvzzxjpzci6ijewmdm0nzy2mzu4mzm1otc5ntiwmcj9.fzao4kjsv2rsh0rbil1zghdko8npmu_9ufo6wex_ti2q9gsilp7xaw7u9cu7ueweoax4dtdpbfmmpvlutcj_sq;    closeablehttpclient client = httpclients.createdefault();    // 要调用的接口url    string url = http://39.103.201.110:30661 /xdap-open/open/process/v1/submit;    httppost post = new httppost(url);    jsonobject jsonobject = null;    try {        //创建请求体并添加数据        stringentity s = new stringentity(date.tostring());        //此处相当于在header里头添加content-type等参数        s.setcontenttype(application/json);        s.setcontentencoding(utf-8);        post.setentity(s);        //此处相当于在authorization里头添加bear token参数信息        post.addheader(authorization, bearer  +assesstoken);        httpresponse res = client.execute(post);        string response1 = entityutils.tostring(res.getentity());        if (res.getstatusline()                .getstatuscode() == httpstatus.sc_ok) {            // 返回json格式:            string result = entityutils.tostring(res.getentity());            jsonobject = jsonobject.parseobject(result);        }    } catch (exception e) {        throw new runtimeexception(e);    }    return jsonobject;} 3、方式二:使用resttemplate方法
spring-boot开发中,resttemplate同样提供了对外访问的接口api,这里主要介绍get和post方法的使用。
get请求
提供了getforobject 、getforentity两种方式,其中getforentity如下三种方法的实现:
get--getforentity,存在以下两种方式重载
1.getforentity(stringurl,class responsetype,object…urlvariables)2.getforentity(uri url,class responsetype) get--getforentity(uri url,class responsetype)
//该方法使用uri对象来替代之前的url和urlvariables参数来指定访问地址和参数绑定。uri是jdk java.net包下的一个类,表示一个统一资源标识符(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();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)resttemplate resttemplate=new resttemplate();mapparams=new hashmap();params.put(name,dada); //responseentityresponseentity=resttemplate.getforentity(http://userservice/user?name={name},string.class,params); get--getforobject,存在以下三种方式重载
1.getforobject(string url,class responsetype,object...urlvariables)2.getforobject(string url,class responsetype,map urlvariables)3.getforobject(uri url,class responsetype) getforobject方法可以理解为对getforentity的进一步封装,它通过httpmessageconverterextractor对http的请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容。
post 请求
post请求提供有postforentity、postforobject和postforlocation三种方式,其中每种方式都有三种方法,下面介绍postforentity的使用方法。
post--postforentity,存在以下三种方式重载
1.postforentity(string url,object request,class responsetype,object...  urivariables) 2.postforentity(string url,object request,class responsetype,map  urivariables) 3.postforentity(uri url,object request,class responsetype) 如下仅演示第二种重载方式
/* * @description post方式获取入参,插入数据并发起流程 * @author lyx * @date 2022/8/24 16:07 * @params * @return */@postmapping(/submit2)public object insertfinancecompensation(@requestbody jsonobject jsonobject) {    string documentid=jsonobject.get(documentid).tostring();    return task2service.submit(documentid);}/* * @description 使用resttimeplate调外部接口 * @author lyx * @date 2022/8/24 16:02 * @params documentid * @return string */public string submit(string documentid){    string assesstoken=eyj0exaioijkv1qilcjhbgcioijiuzuxmij9.eyj4zgfwyxbwawqioiizndgxmju4odk2oti2oty1nzyilcjlehaioje2njeymjy5mdgsimlhdci6mty2mtixotcwocwiegrhchrlbmfudglkijoimzawotgxnja1mte0mduynja5iiwiegrhchvzzxjpzci6ijewmdm0nzy2mzu4mzm1otc5ntiwmcj9.fzao4kjsv2rsh0rbil1zghdko8npmu_9ufo6wex_ti2q9gsilp7xaw7u9cu7ueweoax4dtdpbfmmpvlutcj_sq;    resttemplate resttemplate = new resttemplate();    //创建请求头    httpheaders httpheaders = new httpheaders();    //此处相当于在authorization里头添加bear token参数信息    httpheaders.add(httpheaders.authorization, bearer  + assesstoken);    //此处相当于在header里头添加content-type等参数    httpheaders.add(httpheaders.content_type,application/json);    map map = getmap(documentid);    string jsonstr = json.tojsonstring(map);    //创建请求体并添加数据    httpentity httpentity = new httpentity(map, httpheaders);    string url = http://39.103.201.110:30661/xdap-open/open/process/v1/submit;    responseentity forentity = resttemplate.postforentity(url,httpentity,string.class);//此处三个参数分别是请求地址、请求体以及返回参数类型    return forentity.tostring();} 4、方式三:使用feign进行消费
在maven项目中添加依赖
    org.springframework.cloud    spring-cloud-starter-feign    1.2.2.release 启动类上加上@enablefeignclients
@springbootapplication@enablefeignclients@componentscan(basepackages = {com.definesys.mpaas, com.xdap.* ,com.xdap.*})public class mobilecardapplication {     public static void main(string[] args) {        springapplication.run(mobilecardapplication.class, args);    } } 此处编写接口模拟外部接口供feign调用外部接口方式使用
定义controller
@autowiredprintservice printservice;@postmapping(/outside)public string test(@requestbody testdto testdto) {    return printservice.print(testdto);} 定义service
@servicepublic interface printservice {    public string print(testdto testdto);}定义serviceimplpublic class printserviceimpl implements printservice {     @override    public string print(testdto testdto) {        return 模拟外部系统的接口功能+testdto.getid();    }} 构建feigin的service
定义service
//此处name需要设置不为空,url需要在.properties中设置@service@feignclient(url = ${outside.url}, name = service2)public interface feignservice2 {    @requestmapping(value = /custom/outside, method = requestmethod.post)    @responsebody    public string getmessage(@valid @requestbody testdto testdto);} 定义controller
@autowiredfeignservice2 feignservice2;//测试feign调用外部接口入口@postmapping(/test2)public string test2(@requestbody testdto testdto) {    return feignservice2.getmessage(testdto);} postman测试
此处因为我使用了所在项目,所以需要添加一定的请求头等信息,关于feign的请求头添加也会在后续补充
补充如下:
添加header解决方法
将token等信息放入feign请求头中,主要通过重写requestinterceptor的apply方法实现
定义config
@configurationpublic class feignconfig implements requestinterceptor {    @override    public void apply(requesttemplate requesttemplate) {        //添加token        requesttemplate.header(token, eyj0exaioijkv1qilcjhbgcioijiuzuxmij9.eyj4zgfwyxbwawqioiizndgxmju4odk2oti2oty1nzyilcjlehaioje2njeymjy5mdgsimlhdci6mty2mtixotcwocwiegrhchrlbmfudglkijoimzawotgxnja1mte0mduynja5iiwiegrhchvzzxjpzci6ijewmdm0nzy2mzu4mzm1otc5ntiwmcj9.fzao4kjsv2rsh0rbil1zghdko8npmu_9ufo6wex_ti2q9gsilp7xaw7u9cu7ueweoax4dtdpbfmmpvlutcj_sq);    }} 定义service


全国5G基站建成并开通超过60万个_为5G商用奠定了基础
FCA与硅谷初创公司合作生产电动飞机
这种有序神经元,像你熟知的循环神经网络吗?
联发科“重回”电视芯片赛道,抢抓4K/8K、AI风口
中国电信有望使用TD-LTE
Spring-Boot项目开发中调用apaas接口的三种方式
使用人工智能的施展方法论:做好五个步骤
惊喜还是失望?阿尔法罗密欧能在中国达到宝马三系
美格智能亮相中国企业家博鳌论坛:勇立创新潮头,5G+AIoT开启智能新时代
日产公开电动汽车用非接触充电系统,计划配备于新一代车型
Telia携手爱立信推出首个5G商用服务
麦芒8手机上手评测 智能生活全新体验
OGS全贴合技术的特点和应用简析
5G网络:加速万物互联的世界到来
蔚来短期内不会量产磷酸铁锂汽车
华为与成都高投集团等拟共同收购鼎桥通信100%股权
供应链是未来企业的命脉能力, 为什么要尽早布局IBP?
单片机边沿触发中断响应时刻的测量
飞利浦专业照明成功点亮深圳外环高速公路隧道
SymPy: 符号计算库是什么