maven引用:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.0</version>
</dependency>
get请求:
JSONObject jsonObject = new JSONObject();
jsonObject.put("oldPass","12345678");
jsonObject.put("newPass","12345678");
//1. HttpRequest请求
String body = HttpRequest.get(postURL).form(jsonObject).execute().body();
//2. HttpUtil请求
// 最简单的HTTP请求,可以自动通过header等信息判断编码,不区分HTTP和HTTPS
String result1= HttpUtil.get("https://www.baidu.com");
// 当无法识别页面编码的时候,可以自定义请求页面的编码
String result2= HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);
//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");
String result3= HttpUtil.get("https://www.baidu.com", paramMap);
post请求:
//application/json
String requestParam = jsonObject.toJSONString();
postRes = HttpRequest.post(url).body(requestParam)
.contentType("application/json").execute().body();
JSONObject res = JSONObject.parseObject(postRes);
log.info("接口返回数据:{}", res);
JSONObject data = res.getJSONObject("data");
//x-www-form-urlencoded
String rsp = HttpRequest.post(url)
.contentType("application/x-www-form-urlencoded;charset=GBK")
.charset("GBK")
.form(jsonObject).execute().body();
//表单
String result2 = HttpRequest.post(url)
.header(Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
.form(jsonObject)//表单内容
.timeout(20000)//超时,毫秒
.execute().body();
工具类hutool: https://www.javajike.com/book/hutool/chapter11/b00416d15bfb42199f20b065f5f69320.html