hutool拼装发起请求
时间: 2023-12-16 12:05:07 浏览: 36
Hutool是一个Java工具库,提供了丰富的工具方法,其中包括了发送HTTP请求的工具类HttpUtil。下面是使用Hutool发送HTTP请求的示例代码:
```java
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
public class HttpTest {
public static void main(String[] args) {
// 发送GET请求
HttpResponse response = HttpRequest.get("http://www.baidu.com").execute();
System.out.println(response.body());
// 发送POST请求
String result = HttpRequest.post("http://localhost:8080/test")
.header("Content-Type", "application/json")
.body("{\"name\":\"hutool\",\"age\":18}")
.execute().body();
System.out.println(result);
}
}
```
上述代码中,我们使用了Hutool的HttpRequest类来发送HTTP请求。其中,get()和post()方法用于指定请求的方法,execute()方法用于执行请求并返回响应结果。在发送POST请求时,我们还设置了请求头和请求体。