get请求
String body = HttpUtil.createGet("www.baidu.com").execute().body();
post请求
构建表单POST请求
// 构建表单POST请求
HttpRequest request = HttpRequest.post(url)
.header("Content-Type", "application/x-www-form-urlencoded") // 表单类型的Content-Type
.form("key1", "value1")
.form("key2", "value2");
构建body POST请求
// 构建body POST请求
// 请求的URL
String url = "http://example.com/api/post";
// 构建POST请求
HttpRequest request = HttpRequest.post(url)
.header("Content-Type", "application/json") // 设置请求头
.body("{\"key\":\"value\"}"); // 设置请求体,这里是一个JSON字符串
// 发送请求,并接收响应
HttpResponse response = request.execute();
// 打印响应的内容
System.out.println(response.body());
构建body POST请求,还可以用jsonObject 转换成String
JSONObject jsonObject = new JSONObject();
jsonObject.put("profile_id",userProFileMap.get(authDTO.getUserId()));
jsonObject.put("timezone",authDTO.getTimezone());
jsonObject.put("officeCode",authDTO.getOfficeCode());
String result = HttpUtil.post(updateUpfUserTimezoneUrl, JSON.toJSONString(jsonObject));
put请求
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
public class HutoolPutExample {
public static void main(String[] args) {
// 请求的URL
String url = "http://example.com/api/put";
// 构建PUT请求
HttpRequest request = HttpRequest.put(url)
.header("Content-Type", "application/json") // 设置请求头
.body("{\"key\":\"newValue\"}"); // 设置请求体,这里是一个JSON字符串
// 发送请求,并接收响应
HttpResponse response = request.execute();
// 打印响应的内容
System.out.println(response.body());
}
}
// form的形式传递参数,可以放在url上
// 构建PUT请求
HttpRequest request = HttpRequest.put(url)
.header("Content-Type", "application/json") // 设置请求头
.form("key1", "value1") // 添加URL参数
.form("key2", "value2") // 添加URL参数
.body("{\"additionalKey\":\"additionalValue\"}"); // 设置请求体,这里是一个JSON字符串
// 发送请求,并接收响应
HttpResponse response = request.execute();
// 打印响应的内容
System.out.println(response.body());