java使用RestTemplate封装post请求方式
程序员文章站
2022-06-25 22:23:39
目录使用resttemplate封装post请求resttemplate使用封装1、springboot使用resttemplate(使用apache的httpclient)2、使用jdk原生的2、拦...
使用resttemplate封装post请求
之前笔者写过一篇比较实用的文章 java使用httpclient封装post请求和get的请求,其实java中实现http请求还可以用 resttemplate 完成,下面给出示例代码:
import com.alibaba.fastjson.jsonobject; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.http.*; import org.springframework.http.converter.stringhttpmessageconverter; import org.springframework.web.client.resttemplate; import javax.annotation.postconstruct; import java.nio.charset.charset; public class httphelper { private static logger logger = loggerfactory.getlogger(httphelper.class); private resttemplate resttemplate; private httpheaders httpheaders; @postconstruct public void init() { resttemplate = new resttemplate(); resttemplate.getmessageconverters().add(0, new stringhttpmessageconverter(charset.forname("utf-8"))); httpheaders = new httpheaders(); httpheaders.setcontenttype(org.springframework.http.mediatype.application_json); } /** * post - json * @param params * @return */ public string post(jsonobject params, string url) { logger.info("请求参数:{}", params.tojsonstring()); responseentity<string> response; try { response = resttemplate.exchange( url, httpmethod.post, new httpentity<>(params, httpheaders), string.class); } catch (exception e) { logger.error("请求异常", e); return "请求异常"; } logger.info("响应结果:{}", jsonobject.tojsonstring(response)); if (response.getstatuscode().equals(httpstatus.ok)) { logger.info("请求成功,返回结果:{}", response.getbody()); return response.getbody(); } logger.error("请求失败,http状态码:{},返回结果:{}", response.getstatuscode(), response.getbody()); return response.getbody(); } }
resttemplate 是 spring 提供的用于访问rest服务的客户端,resttemplate 提供了多种便捷访问远程http 服务的方法,能够大大提高客户端的编写效率。
resttemplate使用封装
之前接口调用习惯性使用httpclient,代码复杂,冗余代码多,关心资源回收用起来不是很爽。
resttemplate默认依赖jdk的http连接工具。也可以 通过setrequestfactory属性切换到不同的http源,比如apache httpcomponents、netty、okhttp。
1、springboot使用resttemplate(使用apache的httpclient)
import org.springframework.boot.web.client.resttemplatebuilder; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.http.client.clienthttprequestfactory; import org.springframework.http.client.httpcomponentsclienthttprequestfactory; import org.springframework.http.converter.bytearrayhttpmessageconverter; import org.springframework.http.converter.formhttpmessageconverter; import org.springframework.http.converter.httpmessageconverter; import org.springframework.http.converter.resourcehttpmessageconverter; import org.springframework.http.converter.stringhttpmessageconverter; import org.springframework.http.converter.json.mappingjackson2httpmessageconverter; import org.springframework.http.converter.support.allencompassingformhttpmessageconverter; import org.springframework.web.client.resttemplate; import java.nio.charset.charset; import java.text.simpledateformat; import java.util.arraylist; import java.util.list; import java.util.concurrent.timeunit; @configuration public class resttemplateconfig { @bean public resttemplate getresttemplate() { //手动指定转换器(httpmessageconverter) list<httpmessageconverter<?>> messageconverters = new arraylist<httpmessageconverter<?>>(); messageconverters.add(new bytearrayhttpmessageconverter()); messageconverters.add(new stringhttpmessageconverter(charset.forname("utf-8")));//string强制使用utf-8 messageconverters.add(new resourcehttpmessageconverter()); messageconverters.add(new allencompassingformhttpmessageconverter()); messageconverters.add(new formhttpmessageconverter()); mappingjackson2httpmessageconverter jacksonconverter = new mappingjackson2httpmessageconverter(); jacksonconverter.getobjectmapper().setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss")); messageconverters.add(jacksonconverter); resttemplate resttemplate = new resttemplatebuilder().additionalmessageconverters(messageconverters).build(); resttemplate.setrequestfactory(getclienthttprequestfactory()); return resttemplate; } @bean public clienthttprequestfactory getclienthttprequestfactory() { // 保持长连接配置,需要在头添加keep-alive final connectionkeepalivestrategy mystrategy = new connectionkeepalivestrategy() { @override public long getkeepaliveduration(org.apache.http.httpresponse response, httpcontext context) { // 设置一个链接的最大存活时间 return 5 * 1000l; } }; poolinghttpclientconnectionmanager pollingconnectionmanager = new poolinghttpclientconnectionmanager(30, timeunit.seconds); pollingconnectionmanager.setmaxtotal(2000);//最大连接数 pollingconnectionmanager.setdefaultmaxperroute(200);//同路由的最大连接数 closeablehttpclient closeablehttpclient = httpclientbuilder.create().setconnectionmanager(pollingconnectionmanager).setkeepalivestrategy(mystrategy).build(); httpcomponentsclienthttprequestfactory factory = new httpcomponentsclienthttprequestfactory(closeablehttpclient); factory.setconnecttimeout(3000); factory.setreadtimeout(5000); return factory; } }
2、使用jdk原生的
// 添加消息转换器 list messageconverters = new arraylist(); messageconverters.add(new stringhttpmessageconverter()); messageconverters.add(new mappingjackson2httpmessageconverter()); //如果usej2sehttp申明为true,则使用jdk自带的httpurlconnection simpleclienthttprequestfactory requestfactory = new simpleclienthttprequestfactory(); requestfactory.setreadtimeout(3000); requestfactory.setconnecttimeout(3000); resttemplate = new resttemplate(requestfactory); resttemplate.setmessageconverters(messageconverters); //这里是添加了拦截器 list<clienthttprequestinterceptor> interceptorlist = new arraylist<clienthttprequestinterceptor>(); interceptorlist.add(new requestinteceptor()); resttemplate.setinterceptors(interceptorlist);
2、拦截器实现clienthttprequestinterceptor
(设置头信息的时候回使用到)
public class requestinteceptor implements clienthttprequestinterceptor { @override public clienthttpresponse intercept(httprequest request, byte[] body, clienthttprequestexecution execution) throws ioexception { request.getheaders().setall(appmetadatautil.getapp_metadata()); string traceid = uuid.randomuuid().tostring().replaceall("-", ""); request.getheaders().set("traceid", traceid.tostring()); return execution.execute(request, body); } }
4、常用的方法
string url = queryinfo?userid={userid}&pageindex={pageindex}&pagesize={pagesize}"; hashmap<string,object> parametermap = new hashmap<string,object>(); parametermap.put("userid", userid); parametermap.put("pageindex", pageindex); parametermap.put("pagesize", pagesize); string str = resttemplate.getforobject(url, string.class, parametermap); string result = resttemp.getforobject(requesturl.tostring(), string.class); //post string url = "http://www.xxx.com/queryinfo" string str = resttemplate.postforobject(url, parametermap, string.class); //exchange 设置请求头 httpheaders headers = new httpheaders(); headers.setcontenttype(mediatype.parsemediatype("application/json;charset=utf-8")); headers.add("accept", "application/json;charset=utf-8"); httpentity<string> httpentity = new httpentity<string>("", headers); resttemplate resttemplate = resttemplateutils.getinstance().getresttemplate(); responseentity<string> exchange = resttemplate.exchange(retailorderurl, httpmethod.get, httpentity, string.class); string forobject = exchange.getbody(); multivaluemap<string, object> requestentity = new linkedmultivaluemap<>();
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
上一篇: 铲屎官不欢迎“网红”
推荐阅读
-
JS实现使用POST方式发送请求
-
浅谈Java代码的 微信长链转短链接口使用 post 请求封装Json(实例)
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
PHP使用curl请求实现post方式上传图片文件功能示例
-
浅谈Java代码的 微信长链转短链接口使用 post 请求封装Json(实例)
-
SpringBoot图文教程17—上手就会 RestTemplate 使用指南「Get Post」「设置请求头」
-
安卓中使用OkHttp发送数据请求的两种方式(同、异步的GET、POST) 示例-- Android基础
-
java后端发送http请求使用RestTemplate(简单的都无敌了)
-
java使用RestTemplate封装post请求方式
-
Java Springboot使用RestTemplate发送http请求