Java:利用Hutool工具库简化Java中的HTTP请求操作/使用hutool工具类发送http请求

Java SDK 与 HTTP 请求使用示例
SDK 放入pom中: 
<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>4.1.2</version>
</dependency>
httpUtil使用post和get请求
//指定URL
String url = "https://xxx";

//存放参数
Map mapParam = new HashMap<>();
map.put("A", 100);
map.put("B", 200);

//存放请求头,可以存放多个请求头
HashMap headers = new HashMap<>();
headers.put("xxx", xxx);

//发送get请求并接收响应数据
String result= HttpUtil.createGet(url).addHeaders(headers)
.form(mapParam).execute().body();

//发送post请求并接收响应数据
String result= HttpUtil.createPost(url).body(mapParam)
.addHeaders(headers).execute().body();
test
@Test
public void testHttps() throws Exception {
JSONObject json = new JSONObject();
json.put("username", "xxxx");
json.put("password", "123456.");
String result = HttpRequest.post("https://xxx/users")
.header("Content-Type", "application/json")
.body(json)
.execute().body();
System.out.println(result);
}

post demo
public Response downloadFile(String fileId, String userName) { 
String url ="www.baidu.com" 
String jsonParams = JSON.toJSONString(new xxxx(fileId, userName)); 
Map<String, String> header = new HashMap<>(); 
String body = cn.hutool.http.HttpUtil.createPost(url)
.body(jsonParams).addHeaders(akSkHeader)
.execute().body(); 
//返回的结果转为json
 return JSON.parseObject(body,Response.class); }

get demo
public String getDemo(){
URI uri ="www.baidu.com"; 
//存放请求头,可以存放多个请求头 
HashMap<String, String> headers = new HashMap<>(); 
addConsoleHeadersMap(headers); 
//请求头加上headers.put("Accept", "application/json")
headers.put("Accept", "application/json");
 HashMap<String, Object> params = new HashMap<>(); 
params.put("systemId", systemId); 
//发送get请求并接收响应数据 
String result = HttpUtil.createGet(uri.toString())
.addHeaders(headers).form(params).execute().body();
return result;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java皇帝

有帮助就赏点吧,博主点杯水喝喝

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值