欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Hutool——发送http请求案例

Hutool——发送http请求案例

2024/10/23 11:23:57 来源:https://blog.csdn.net/qq_38322527/article/details/140766614  浏览:    关键词:Hutool——发送http请求案例

文章目录

  • 前言
  • 依赖环境
  • Hutool 请求验证
    • 准备第三方接口
    • 编写接口调用上述定义接口
  • 自测验证
    • get 请求
    • post 非常规 application/x-www-form-urlencoded
    • post 常规 application/json

前言

在实际开发过程中,微服务环境下往往采取openfeign实现服务与服务之间的请求调用。但有时候需要调用第三方API的情况,虽然在spring boot 框架中提供了RestTemplate请求模板,但这个不怎么好用。

市面上支持http调用的框架技术很多,比如okhttp等。本篇文章重点说明Hutool给我们封装的请求方法类。

依赖环境

使用Hutool,需要引入对应的依赖。如下:

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.5</version>
</dependency>

Hutool 请求验证

准备第三方接口

准备get常规 post非常规post两种接口。

import cn.xj.model.Result;
import cn.xj.model.UserVo;
import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/test")
public class TestController {/*** 常规 get 请求* @param name* @param age* @return*/@GetMapping("/get")public Result get(String name,Integer age){Map<String,Object> map = new HashMap<>();map.put("name",name);map.put("age",age);return Result.success(map);}/*** post 请求,未指定 Content-Type 时,默认是 application/json,参数传递在boby* 若指定类型为 application/x-www-form-urlencoded,参数传递在请求头上,类似get* @param name* @param age* @return*/@PostMapping("/post1")public Result post1(@RequestParam String name,@RequestParam Integer age){Map<String,Object> map = new HashMap<>();map.put("name",name);map.put("age",age);return Result.success(map);}@PostMapping("/post2")public Result post2(@RequestBody UserVo body){Map<String,Object> map = new HashMap<>();map.put("name2",body.getName());map.put("age2",body.getAge());map.put("body",body);return Result.success(map);}
}

【注意】这里做一点说明。

post 请求,
未指定 Content-Type 时,默认是 application/json,参数传递在boby
若指定类型为 application/x-www-form-urlencoded,参数传递在请求头上,类似get

参考资料:
Axios请求头中常见的Content-Type常见的三种格式
在这里插入图片描述

编写接口调用上述定义接口

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.xj.model.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/http")
public class HttpTestController {/*** 调用post 接口发送get请求* @return*/@PostMapping("/post/get")public Result getRequest(){// 设定headermap  get 请求对请求头的设置没影响HashMap<String, String> headerMap = new HashMap<>();headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()); // application/json//headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.FORM_URLENCODED.getValue()); // application/x-www-form-urlencodedHashMap<String, Object> bodyMap = new HashMap<>();bodyMap.put("name","香蕉");bodyMap.put("age","20");// 请求HttpResponse response = HttpRequest.get("http://localhost:80/test/get").form(bodyMap) // url 上加参数.addHeaders(headerMap).timeout(20000).execute();return Result.success(response.body());}/*** 调用post 查询第三方post请求* @param type 类别*             0、application/x-www-form-urlencoded*             1、application/json* @return*/@PostMapping("/post/post")public Result postRequest(@RequestParam Integer type){HashMap<String, Object> bodyMap = new HashMap<>();bodyMap.put("name","香蕉");bodyMap.put("age","20");String bodyStr = "";String url = "";HashMap<String, String> headerMap = new HashMap<>();if(0 == type){headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.FORM_URLENCODED.getValue()); // application/x-www-form-urlencoded// post 请求默认是 application/json,如果是 application/x-www-form-urlencoded 则需要保证参数在url后StringBuilder sb = new StringBuilder();for (Map.Entry<String, Object> stringObjectEntry : bodyMap.entrySet()) {String key = stringObjectEntry.getKey();Object value = stringObjectEntry.getValue();sb.append(key).append("=").append(value).append("&");}bodyStr = sb.deleteCharAt(sb.length() - 1).toString();url = "http://localhost:80/test/post1";}else{headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()); // application/jsonbodyStr = JSONObject.toJSONString(bodyMap);url = "http://localhost:80/test/post2";}// 请求HttpResponse response = HttpRequest.post(url)// .form(bodyMap) // url 上加参数.body(bodyStr).addHeaders(headerMap).timeout(20000).execute();return Result.success(response.body());}
}

自测验证

get 请求

使用get请求时,不管设定的Content-Typeapplication/json,亦或者application/x-www-form-urlencoded,传递数据在body时,都不会被解析。

http://localhost/http/post/get

在这里插入图片描述

post 非常规 application/x-www-form-urlencoded

http://localhost/http/post/post?type=0
在这里插入图片描述

请求后的数据返回样式如下:
在这里插入图片描述

post 常规 application/json

http://localhost/http/post/post?type=2
在这里插入图片描述
请求后的数据返回样式如下:
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com