hutool 发送http请求
时间: 2023-10-03 22:11:26 浏览: 55
你可以使用Hutool库来发送HTTP请求。Hutool是一个Java工具包,提供了丰富的工具方法和简化开发的功能。
下面是使用Hutool发送HTTP请求的示例代码:
```java
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
public class HttpExample {
public static void main(String[] args) {
// 发送GET请求
HttpResponse response = HttpRequest.get("http://www.example.com").execute();
if (response.getStatus() == HttpStatus.HTTP_OK) {
String result = response.body();
System.out.println(result);
}
// 发送POST请求
String postData = "name=John&age=25";
HttpResponse postResponse = HttpRequest.post("http://www.example.com")
.body(postData)
.execute();
if (postResponse.getStatus() == HttpStatus.HTTP_OK) {
String result = postResponse.body();
System.out.println(result);
}
}
}
```
上面的示例代码中,首先使用`HttpRequest.get()`方法发送了一个GET请求,并使用`execute()`方法执行请求,返回一个`HttpResponse`对象。然后通过判断返回的状态码是否为HTTP_OK(200)来判断请求是否成功,如果成功,则可以通过`body()`方法获取响应体的内容。
发送POST请求与发送GET请求类似,只需使用`HttpRequest.post()`方法,并使用`body()`方法设置POST请求的参数。
需要注意的是,在使用Hutool发送HTTP请求前,需要在项目中引入Hutool依赖。