Spring远程调用HttpClient/RestTemplate的方法
一、HttpClient
两个系统间如何互相访问?两个tomcat上的项目如何互相访问?
采用HttpClient实现跨系统的接口调用。
介绍:
官网:http://hc.apache.org/index.html
现在也叫:HttpComponents
HttpClient可以发送get、post、put、delete、...等请求
使用:
导入坐标
org.apache.httpcomponents httpclient 4.4
//1、使用HttpClient发起Get请求
publicclassDoGET{
publicstaticvoidmain(String[]args)throwsException{
//创建Httpclient对象,相当于打开了浏览器
CloseableHttpClienthttpclient=HttpClients.createDefault();
//创建HttpGet请求,相当于在浏览器输入地址
HttpGethttpGet=newHttpGet("http://www.baidu.com/");
CloseableHttpResponseresponse=null;
try{
//执行请求,相当于敲完地址后按下回车。获取响应
response=httpclient.execute(httpGet);
//判断返回状态是否为200
if(response.getStatusLine().getStatusCode()==200){
//解析响应,获取数据
Stringcontent=EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(content);
}
}finally{
if(response!=null){
//关闭资源
response.close();
}
//关闭浏览器
httpclient.close();
}
}
}
//2、使用HttpClient发起带参数的Get请求
publicclassDoGETParam{
publicstaticvoidmain(String[]args)throwsException{
//创建Httpclient对象
CloseableHttpClienthttpclient=HttpClients.createDefault();
//创建URI对象,并且设置请求参数
URIuri=newURIBuilder("http://www.baidu.com/s").setParameter("wd","java").build();
//创建httpGET请求
HttpGethttpGet=newHttpGet(uri);
//HttpGetget=newHttpGet("http://www.baidu.com/s?wd=java");
CloseableHttpResponseresponse=null;
try{
//执行请求
response=httpclient.execute(httpGet);
//判断返回状态是否为200
if(response.getStatusLine().getStatusCode()==200){
//解析响应数据
Stringcontent=EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(content);
}
}finally{
if(response!=null){
response.close();
}
httpclient.close();
}
}
}
//3、使用HttpClient发起POST请求
publicclassDoPOST{
publicstaticvoidmain(String[]args)throwsException{
//创建Httpclient对象
CloseableHttpClienthttpclient=HttpClients.createDefault();
//创建httpPOST请求
HttpPosthttpPost=newHttpPost("http://www.oschina.net/");
//把自己伪装成浏览器。否则开源中国会拦截访问
httpPost.setHeader("User-Agent","Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/56.0.2924.87Safari/537.36");
CloseableHttpResponseresponse=null;
try{
//执行请求
response=httpclient.execute(httpPost);
//判断返回状态是否为200
if(response.getStatusLine().getStatusCode()==200){
//解析响应数据
Stringcontent=EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(content);
}
}finally{
if(response!=null){
response.close();
}
//关闭浏览器
httpclient.close();
}
}
}
//4、使用HttpClient发起带有参数的POST请求
publicclassDoPOSTParam{
publicstaticvoidmain(String[]args)throwsException{
//创建Httpclient对象
CloseableHttpClienthttpclient=HttpClients.createDefault();
//创建httpPOST请求,访问开源中国
HttpPosthttpPost=newHttpPost("http://www.oschina.net/search");
//根据开源中国的请求需要,设置post请求参数
Listparameters=newArrayList(0);
parameters.add(newBasicNameValuePair("scope","project"));
parameters.add(newBasicNameValuePair("q","java"));
parameters.add(newBasicNameValuePair("fromerr","8bDnUWwC"));
//构造一个form表单式的实体
UrlEncodedFormEntityformEntity=newUrlEncodedFormEntity(parameters);
//将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
CloseableHttpResponseresponse=null;
try{
//执行请求
response=httpclient.execute(httpPost);
//判断返回状态是否为200
if(response.getStatusLine().getStatusCode()==200){
//解析响应体
Stringcontent=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开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多。
导入坐标
org.springframework.boot spring-boot-starter-web
创建RestTemplate对象
@Configuration//加上这个注解作用,可以被Spring扫描
publicclassRestTemplateConfig{
/**
*创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
*@return
*/
@Bean
publicRestTemplaterestTemplate(){
RestTemplaterestTemplate=newRestTemplate();
//主要解决中文乱码
restTemplate.getMessageConverters().set(1,newStringHttpMessageConverter(StandardCharsets.UTF_8));
returnrestTemplate;
}
}
RestTempController
importorg.springframework.http.ResponseEntity;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.client.RestTemplate;
importjavax.annotation.Resource;
@RestController
@RequestMapping("/consumer")
publicclassConsumerController{
//从Spring的容器中获取restTemplate
@Resource
privateRestTemplaterestTemplate;
/**
*通过Get请求,保存数据
*/
@GetMapping("/{id}")
publicResponseEntityfindById(@PathVariableIntegerid){
//发起远程请求:通过RestTemplate发起get请求
ResponseEntityentity=restTemplate.getForEntity("http://localhost:8090/goods2/1",String.class);
System.out.println("entity.getStatusCode():"+entity.getStatusCode());
System.out.println(entity.getBody());
returnentity;
}
/**
*通过Post请求,保存数据
*/
@PostMapping
publicResponseEntitysaveGoods(@RequestBodyGoodsgoods){
//通过RestTemplate发起远程请求
/**
*第一个参数:远程地址URI
*第二个参数:数据
*第三个参数:返回值类型
*/
ResponseEntityentity=restTemplate.postForEntity("http://localhost:8090/goods2",goods,String.class);
System.out.println("entity.getStatusCode():"+entity.getStatusCode());
System.out.println(entity.getBody());
returnentity;
}
@PutMapping
publicResponseEntityupdateGoods(@RequestBodyGoodsgoods){
restTemplate.put("http://localhost:8090/goods2",goods);
returnnewResponseEntity<>("修改成功",HttpStatus.OK);
}
@DeleteMapping("/{id}")
publicResponseEntitydeleteById(@PathVariableIntegerid){
restTemplate.delete("http://localhost:8090/goods2/"+id);
returnnewResponseEntity<>("删除成功",HttpStatus.OK);
}
}
只用maven不用springboot框架时只需要导入依赖到pom文件
org.springframework spring-web
直接new RestTemplate()对象使用即可
到此这篇关于Spring远程调用HttpClient/RestTemplate的方法的文章就介绍到这了,更多相关Spring远程调用HttpClient/RestTemplate内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。