Spring远程调用HttpClient/RestTemplate的方法
程序员文章站
2022-07-03 19:28:53
一、httpclient两个系统间如何互相访问?两个tomcat上的项目如何互相访问? 采用httpclient实现跨系统的接口调用。介绍:官网:http://hc.apache.org/inde...
一、httpclient
两个系统间如何互相访问?两个tomcat上的项目如何互相访问?
采用httpclient实现跨系统的接口调用。
介绍:
官网:http://hc.apache.org/index.html
现在也叫:httpcomponents
httpclient可以发送get、post、put、delete、...等请求
使用:
导入坐标
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.4</version> </dependency>
//1、使用httpclient发起get请求 public class doget { public static void main(string[] args) throws exception { // 创建httpclient对象,相当于打开了浏览器 closeablehttpclient httpclient = httpclients.createdefault(); // 创建httpget请求,相当于在浏览器输入地址 httpget httpget = new httpget("http://www.baidu.com/"); closeablehttpresponse response = null; try { // 执行请求,相当于敲完地址后按下回车。获取响应 response = httpclient.execute(httpget); // 判断返回状态是否为200 if (response.getstatusline().getstatuscode() == 200) { // 解析响应,获取数据 string content = entityutils.tostring(response.getentity(), "utf-8"); system.out.println(content); } } finally { if (response != null) { // 关闭资源 response.close(); } // 关闭浏览器 httpclient.close(); } } } //2、使用httpclient发起带参数的get请求 public class dogetparam { public static void main(string[] args) throws exception { // 创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); // 创建uri对象,并且设置请求参数 uri uri = new uribuilder("http://www.baidu.com/s").setparameter("wd", "java").build(); // 创建http get请求 httpget httpget = new httpget(uri); // httpget get = new httpget("http://www.baidu.com/s?wd=java"); closeablehttpresponse response = null; try { // 执行请求 response = httpclient.execute(httpget); // 判断返回状态是否为200 if (response.getstatusline().getstatuscode() == 200) { // 解析响应数据 string content = entityutils.tostring(response.getentity(), "utf-8"); system.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } } //3、使用httpclient发起post请求 public class dopost { public static void main(string[] args) throws exception { // 创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); // 创建http post请求 httppost httppost = new httppost("http://www.oschina.net/"); // 把自己伪装成浏览器。否则开源中国会拦截访问 httppost.setheader("user-agent", "mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/56.0.2924.87 safari/537.36"); closeablehttpresponse response = null; try { // 执行请求 response = httpclient.execute(httppost); // 判断返回状态是否为200 if (response.getstatusline().getstatuscode() == 200) { // 解析响应数据 string content = entityutils.tostring(response.getentity(), "utf-8"); system.out.println(content); } } finally { if (response != null) { response.close(); } // 关闭浏览器 httpclient.close(); } } } //4、使用httpclient发起带有参数的post请求 public class dopostparam { public static void main(string[] args) throws exception { // 创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); // 创建http post请求,访问开源中国 httppost httppost = new httppost("http://www.oschina.net/search"); // 根据开源中国的请求需要,设置post请求参数 list<namevaluepair> parameters = new arraylist<namevaluepair>(0); parameters.add(new basicnamevaluepair("scope", "project")); parameters.add(new basicnamevaluepair("q", "java")); parameters.add(new basicnamevaluepair("fromerr", "8bdnuwwc")); // 构造一个form表单式的实体 urlencodedformentity formentity = new urlencodedformentity(parameters); // 将请求实体设置到httppost对象中 httppost.setentity(formentity); closeablehttpresponse response = null; try { // 执行请求 response = httpclient.execute(httppost); // 判断返回状态是否为200 if (response.getstatusline().getstatuscode() == 200) { // 解析响应体 string content = entityutils.tostring(response.getentity(), "utf-8"); system.out.println(content); } } finally { if (response != null) { response.close(); } // 关闭浏览器 httpclient.close(); } } }
二、resttemplate
resttemplate是spring提供的用于访问rest服务的客户端,resttemplate提供了多种便捷访问远程http服务的方法
http开发是用apache的httpclient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多。
导入坐标
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency>
创建resttemplate对象
@configuration//加上这个注解作用,可以被spring扫描 public class resttemplateconfig { /** * 创建resttemplate对象,将resttemplate对象的生命周期的管理交给spring * @return */ @bean public resttemplate resttemplate(){ resttemplate resttemplate = new resttemplate(); //主要解决中文乱码 resttemplate.getmessageconverters().set(1, new stringhttpmessageconverter(standardcharsets.utf_8)); return resttemplate; } }
resttempcontroller
import org.springframework.http.responseentity; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.client.resttemplate; import javax.annotation.resource; @restcontroller @requestmapping("/consumer") public class consumercontroller { // 从spring的容器中获取resttemplate @resource private resttemplate resttemplate; /** * 通过get请求,保存数据 */ @getmapping("/{id}") public responseentity<string> findbyid(@pathvariable integer id){ //发起远程请求:通过resttemplate发起get请求 responseentity<string> entity = resttemplate.getforentity("http://localhost:8090/goods2/1", string.class); system.out.println("entity.getstatuscode():"+entity.getstatuscode()); system.out.println(entity.getbody()); return entity; } /** * 通过post请求,保存数据 */ @postmapping public responseentity<string> savegoods(@requestbody goods goods){ //通过resttemplate发起远程请求 /** * 第一个参数:远程地址uri * 第二个参数:数据 * 第三个参数:返回值类型 */ responseentity<string> entity = resttemplate.postforentity("http://localhost:8090/goods2", goods, string.class); system.out.println("entity.getstatuscode():"+entity.getstatuscode()); system.out.println(entity.getbody()); return entity; } @putmapping public responseentity<string> updategoods(@requestbody goods goods){ resttemplate.put("http://localhost:8090/goods2",goods); return new responseentity<>("修改成功", httpstatus.ok); } @deletemapping("/{id}") public responseentity<string> deletebyid(@pathvariable integer id){ resttemplate.delete("http://localhost:8090/goods2/"+id); return new responseentity<>("删除成功", httpstatus.ok); } }
只用maven不用springboot框架时只需要导入依赖到pom文件
<dependency> <groupid>org.springframework</groupid> <artifactid>spring-web</artifactid> </dependency>
直接new resttemplate()对象使用即可
到此这篇关于spring远程调用httpclient/resttemplate的方法的文章就介绍到这了,更多相关spring远程调用httpclient/resttemplate内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
下一篇: 喵星人原来还有这种操作啊