相关文章推荐
慷慨大方的火腿肠  ·  .net core ...·  6 月前    · 
没有腹肌的麦片  ·  Loading Related ...·  1 年前    · 
气宇轩昂的蜡烛  ·  com.microsoft.sqlserve ...·  1 年前    · 
首发于 编程白话文
常用的http接口调用方法

常用的http接口调用方法

代码请求Get/POST方法

Get的两种常见方法

     String companyId ="A2502199F831959AE053140F0AC60159";
     String  CompanyInfoUrl ="http://192.168.181.143/cttic-egov-rbm/";
     //获取管理船舶接口数据
     String url=CompanyInfoUrl;
     //入参方式1
     url=url+"txsh/queryPage?companyId="+companyId;
     JSONObject jsonObject = HttpsUtils.doGet(url);
     //入参方式2
     //获取管理船舶接口数据
     String url1=CompanyInfoUrl;
     //入参方式1
     url1=url1+"txsh/queryPage";
     HashMap<String, Object> objectMap = new HashMap<>();
     objectMap.put("companyId",companyId);
     JSONObject jsonObject1 = HttpsUtils.doGet(url1, objectMap);

方法二

Get请求(无参)

 public static void noArgsGetHttp() throws IOException {
     // 定义 httpclient
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     // 创建 httpGet
     HttpGet httpGet = new HttpGet("http://www.baidu.com");
     // 定义返回结果
     CloseableHttpResponse execute = null;
     // 发送执行(执行get请求)
     execute = httpClient.execute(httpGet);
     // 获取返回值
     HttpEntity entity = execute.getEntity();
     System.out.println("响应状态为:" + execute.getStatusLine());
     if (Objects.nonNull(entity)) {
         System.out.println("响应内容长度为:" + entity.getContentLength());
         System.out.println("响应内容为:" + EntityUtils.toString(entity));
     // 释放资源
     if (httpClient != null) {
         httpClient.close();
     if (execute != null) {
         execute.close();
 }

Get请求无参核心代码

 // 定义 httpclient
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     // 创建 httpGet
     HttpGet httpGet = new HttpGet("http://www.baidu.com");
     // 定义返回结果
     CloseableHttpResponse execute = null;
     // 发送执行(执行get请求)
     execute = httpClient.execute(httpGet);
     // 获取返回值
     HttpEntity entity = execute.getEntity();

get请求公共方法

  /**
      * get无参请求-公共方法
      * @throws IOException
     public static void noArgsGetHttp(String url) throws IOException {
         // 定义 httpclient
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
         // 创建 httpGet
         HttpGet httpGet = new HttpGet(url);
         // 定义返回结果
         CloseableHttpResponse execute = null;
         // 发送执行(执行get请求)
         execute = httpClient.execute(httpGet);
         // 获取返回值
         HttpEntity entity = execute.getEntity();
     }


Get请求(有参)

 public static void haveArgsGetHttp() throws IOException, URISyntaxException {
     // 定义 httpclient
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     // 创建参数列表
     List<NameValuePair> valueParamsList = new ArrayList<>();
     //添加参数
     valueParamsList.add(new BasicNameValuePair("studentId","1"));
     // 创建对应请求 Uri
     URI uri = new URIBuilder()
         .setScheme("http")
         .setHost("localhost")
         .setPath("/getStudentInfo")
         .setParameters(valueParamsList)
         .build();
     // 根据 Uri 创建 httpGet
     HttpGet httpGet = new HttpGet(uri);
     // 定义返回结果
     CloseableHttpResponse execute = null;
     // 发送执行(发送请求)
     execute = httpClient.execute(httpGet);
     // 获取返回值
     HttpEntity entity = execute.getEntity();
     System.out.println("响应状态为:" + execute.getStatusLine());
     if (Objects.nonNull(entity)) {
         System.out.println("响应内容长度为:" + entity.getContentLength());
         System.out.println("响应内容为:" + EntityUtils.toString(entity));
     // 释放资源
     if (httpClient != null) {
         httpClient.close();
     if (execute != null) {
         execute.close();
 }

Get有参核心请求代码

  // 定义 httpclient
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     // 创建参数列表
     List<NameValuePair> valueParamsList = new ArrayList<>();
     //添加参数
     valueParamsList.add(new BasicNameValuePair("studentId","1"));
     // 创建对应请求 Uri
     URI uri = new URIBuilder()
         .setScheme("http")
         .setHost("localhost")
         .setPath("/getStudentInfo")
         .setParameters(valueParamsList)
         .build();
     // 根据 Uri 创建 httpGet
     HttpGet httpGet = new HttpGet(uri);
     // 定义返回结果
     CloseableHttpResponse execute = null;
     // 发送执行(发送请求)
     execute = httpClient.execute(httpGet);
     // 获取返回值
     HttpEntity entity = execute.getEntity();

get请求公共方法

 /**
      * Get请求有参通用方法
      * @param params 请求参数
      * @throws IOException
      * @throws URISyntaxException
     public static void haveArgsGetHttp(Map<String, Object> params) throws IOException, URISyntaxException {
         try {
             // 定义 httpclient
             CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             //通用入参(参数已键值对的形式)
             List<Map<String, Object>> valueParamsList = new ArrayList<>();
             valueParamsList.add(params);
             // 创建对应请求 Uri
             URI uri = new URIBuilder()
                     .setScheme("http")
                     .setHost("localhost")
                     .setPath("/getStudentInfo")
                     .setParameters((NameValuePair) valueParamsList)
                     .build();
             // 根据 Uri 创建 httpGet
             HttpGet httpGet = new HttpGet(uri);
             // 定义返回结果
             CloseableHttpResponse execute = null;
             // 发送执行(发送请求)
             execute = httpClient.execute(httpGet);
         } catch (URISyntaxException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
     }


Post请求

 /**
 * post 有参数
 public static void haveArgsPosthttp() throws IOException {
     // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     // 创建Post请求
     //设置请求路径
     HttpPost httpPost = new HttpPost("http://localhost:12345/posttest");
     //构建参数实体类
     JSONUtil.Student student = new JSONUtil.Student();
     student.setName("潘晓婷");
     student.setAge(18);
     //将参数转换为json格式
     String jsonString = JSON.toJSONString(student);
     //设置参数格式类型
     StringEntity entity = new StringEntity(jsonString, "UTF-8");
     // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
     httpPost.setEntity(entity);
     httpPost.setHeader("Content-Type", "application/json;charset=utf8");
     // 响应模型(发送post请求)
     CloseableHttpResponse response = httpClient.execute(httpPost);
     // 从响应模型中获取响应实体
     HttpEntity responseEntity = response.getEntity();
     System.out.println("响应状态为:" + response.getStatusLine());
     if (responseEntity != null) {
         System.out.println("响应内容长度为:" + responseEntity.getContentLength());
         System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
     // 释放资源
     if (httpClient != null) {
         httpClient.close();
     if (response != null) {
         response.close();
 }

Post请求核心代码

   // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     // 创建Post请求
     //设置请求路径
     HttpPost httpPost = new HttpPost("http://localhost:12345/posttest");
     //构建参数实体类
     Student student = new Student();
     student.setName("潘晓婷");
     student.setAge(18);
     //将参数转换为json格式
     String jsonString = JSON.toJSONString(student);
     //设置参数格式类型
     StringEntity entity = new StringEntity(jsonString, "UTF-8");
     // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
     httpPost.setEntity(entity);
     //设置请求头
     httpPost.setHeader("Content-Type", "application/json;charset=utf8");
     // 响应模型(发送post请求)
     CloseableHttpResponse response = httpClient.execute(httpPost);
     // 从响应模型中获取响应实体
     HttpEntity responseEntity = response.getEntity();

Post请求公共方法

 /**
      * post请求公共方法
      * @param params 请求参数-实体类
      * @param url 请求url
      * @throws IOException
     public static void haveArgsPosthttp(T params,String url) throws IOException {
         // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
         // 创建Post请求
         //设置请求路径
         HttpPost httpPost = new HttpPost(url);
         //将参数转换为json格式
         String jsonString = JSON.toJSONString(params);
         //设置参数格式类型
         StringEntity entity = new StringEntity(jsonString, "UTF-8");
         // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
         httpPost.setEntity(entity);
         httpPost.setHeader("Content-Type", "application/json;charset=utf8");
         // 响应模型(发送post请求)
         CloseableHttpResponse response = httpClient.execute(httpPost);
         // 从响应模型中获取响应实体
         HttpEntity responseEntity = response.getEntity();
         System.out.println("响应状态为:" + response.getStatusLine());
         if (responseEntity != null) {
             System.out.println("响应内容长度为:" + responseEntity.getContentLength());
             System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
         // 释放资源
         if (httpClient != null) {
             httpClient.close();
         if (response != null) {
             response.close();
     }


RestTemplate远程请求接口

restTemplate是什么

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

之前的HTTP开发是用apache的HttpClient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多。

restTemplate如何使用

使用步骤

  • 引入依赖
  • 设置配置类,将restTemplate配置到bean中
  • 直接在控制层导入restTemplate相关配置,调用post/get请求

引入依赖

使用的是springboot的web相关的包

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

创建实体类

 package com.czxy.ssm.pojo;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 @Data//相当于拥有了getter、setter、toString方法
 @AllArgsConstructor//全参构造
 @NoArgsConstructor//空参构造
 public class Goods {
     public Integer id;
     private String name;
     private String image;
     private Double price;
 } 

配置RestTemplate注入到Bean

 package com.czxy.ssm.config;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.client.RestTemplate;
  * RestTemplate工具类,主要用来提供RestTemplate对象
 @Configuration//加上这个注解作用,可以被Spring扫描
 public class RestTemplateConfig {
      * 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
     @Bean
     public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        //设置中文乱码问题方式一
       // restTemplate.getMessageConverters().add(1,new     StringHttpMessageConverter(Charset.forName("UTF-8")));
        // 设置中文乱码问题方式二
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
         return new RestTemplate();
 

在控制层直接调用

 package com.czxy.ssm.controller;
 import com.czxy.ssm.pojo.Goods;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.client.RestTemplate;
  * 本项目不连接数据库,通过RestTemplate发出get、post、put、delete请求,
  * 请求Goods-project项目中controller的方法
  * 这是基于Ribbon + RestTemplate时,利用RestTemplate对Http请求的封装处理,形成了一套模板化的调用方法
 @RestController
 @RequestMapping("/rest")
 public class RestTempController {
     // 从Spring的容器中获取restTemplate
     @Autowired
     private RestTemplate restTemplate;
      * 通过/id查询
      * http://localhost:8090/goods2 -->分页查找
     @GetMapping("/{id}")
     public ResponseEntity<String> findByPage(@PathVariable Integer id){
          * 第一个参数:url
          * 第二个参数:返回值类型
         ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080/goods2/"+id, String.class);
         System.out.println("状态码:"+entity.getStatusCode());
         System.out.println("响应体"+entity.getBody());
         return ResponseEntity.ok(entity.getBody());
      * 添加数据
     @PostMapping
     public ResponseEntity<String> addGoods(@RequestBody Goods goods){
          * 第一个参数:url
          * 第二个参数:数据
          * 第三个参数:返回值类型
         ResponseEntity<String> entity = restTemplate.postForEntity("http://localhost:8080/goods2", goods, String.class);
         return entity;
      * 修改数据
     @PutMapping
     public ResponseEntity<String> updateGoods(@RequestBody Goods goods){
         // 第一个参数:url
         // 第二个参数:对象,数据
         restTemplate.put("http://localhost:8080/goods2",goods);
 //      return new ResponseEntity<>("成功", HttpStatus.OK);
         return ResponseEntity.ok("修改成功");
      * 根据/id删除
     @DeleteMapping("/{id}")