Spring远程调用HttpClient/RestTemplate的方法

 更新时间:2021年03月06日 12:13:51   作者:依旧ฅ=ฅ  
这篇文章主要介绍了Spring远程调用HttpClient/RestTemplate的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅谈Mybatis获取参数值的方式

    浅谈Mybatis获取参数值的方式

    本文主要介绍了Mybatis获取参数值的方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • postman中POST请求时参数包含参数list设置方式

    postman中POST请求时参数包含参数list设置方式

    这篇文章主要介绍了postman中POST请求时参数包含参数list设置方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Java 8函数式接口之BinaryOperator使用示例详解

    Java 8函数式接口之BinaryOperator使用示例详解

    这篇文章主要大家介绍了Java 8函数式接口之BinaryOperator,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • Java中打jar包以及如何调用包方法演示

    Java中打jar包以及如何调用包方法演示

    这篇文章主要给大家介绍了关于Java中打jar包以及如何调用包的相关资料,jar包的全称是java archive,jar包本质就是一种压缩包,在Java开发中一般是用来压缩类的一个包,需要的朋友可以参考下
    2023-09-09
  • PowerJob的DatabaseMonitorAspect源码流程

    PowerJob的DatabaseMonitorAspect源码流程

    这篇文章主要为大家介绍了PowerJob的DatabaseMonitorAspect源码流程解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • Java中JSONObject和Map<String, Object>的转换方法

    Java中JSONObject和Map<String, Object>的转换方法

    平时对接口时,经常遇到json字符串和map对象之间的交互,这篇文章主要给大家介绍了关于Java中JSONObject和Map<String, Object>的转换方法,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-07-07
  • 新版SpringSecurity5.x使用与配置详解

    新版SpringSecurity5.x使用与配置详解

    Spring Security是一个强大且高度可定制的身份验证和访问控制框架,本文主要介绍了新版SpringSecurity5.x使用与配置详解,具有一定的参考价值,感兴趣的可以了解一下
    2024-08-08
  • java的多线程用法编程总结

    java的多线程用法编程总结

    本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。
    2016-10-10
  • 解决fastjson泛型转换报错的解决方法

    解决fastjson泛型转换报错的解决方法

    这篇文章主要介绍了解决fastjson泛型转换报错的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Spring Boot中的SpringSecurity基础教程

    Spring Boot中的SpringSecurity基础教程

    Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权,这篇文章主要介绍了Spring Boot中的SpringSecurity学习,需要的朋友可以参考下
    2023-01-01

最新评论