hutool-http使用示例
时间: 2023-07-11 20:47:49 浏览: 65
好的,以下是一个简单的hutool-http使用示例:
```java
import cn.hutool.http.HttpUtil;
public class HttpDemo {
public static void main(String[] args) {
// 发送GET请求
String result = HttpUtil.get("https://www.baidu.com");
System.out.println(result);
// 发送POST请求
String url = "http://localhost:8080/login";
String paramJson = "{\"username\":\"admin\",\"password\":\"123456\"}";
String result2 = HttpUtil.post(url, paramJson);
System.out.println(result2);
}
}
```
在这个示例中,我们使用HttpUtil类的get和post方法分别发送了GET和POST请求。其中,get方法发送了一个请求到百度首页,获取了页面内容并打印输出。post方法发送了一个登录请求到本地服务器,并将结果打印输出。这只是一个简单的示例,hutool-http还支持更多的请求方式和参数配置,您可以根据自己的需求进行使用和配置。
相关问题
curl 转换hutool Hutool-http
使用Hutool的HttpUtil可以实现类似curl的功能,以下是一个简单的示例代码:
```java
import cn.hutool.http.HttpUtil;
public class Test {
public static void main(String[] args) {
// 设置请求头
String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3";
String referer = "https://www.baidu.com/";
String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
String charset = "UTF-8";
String contentType = "application/x-www-form-urlencoded";
HttpUtil.createGet("http://www.hutool.cn")
.header("User-Agent", userAgent)
.header("Referer", referer)
.header("Accept", accept)
.charset(charset)
.contentType(contentType)
// 设置请求参数
.form("key1", "value1")
.form("key2", "value2")
.execute();
}
}
```
以上代码实现了一个GET请求,设置了请求头和请求参数。如果需要发送POST请求,只需要将`HttpUtil.createGet()`改为`HttpUtil.createPost()`,并使用`body()`方法设置请求体即可。
注意:Hutool-http需要引入Hutool-all依赖。
使用hutool如何接收http并解析
使用Hutool接收HTTP请求并解析可以通过HttpServer类来实现。下面是一个简单的示例代码:
```java
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.http.server.HttpServer;
public class MyHttpServer {
public static void main(String[] args) {
HttpServer server = new HttpServer(8888);
server.addAction("/", (req, res) -> {
HttpServerRequest request = req.getHttpServerRequest();
HttpServerResponse response = res.getHttpServerResponse();
String body = IoUtil.read(request.getInputStream(), "UTF-8");
System.out.println("接收到请求:" + body);
// 解析请求,进行相应的处理
// ...
response.write("Hello World");
});
server.start();
}
}
```
在这个示例中,我们创建了一个端口为8888的HttpServer,并添加了一个根路径的处理器。在请求到达时,我们可以通过`request.getInputStream()`方法获取请求内容,然后进行解析和处理。在处理完成后,我们可以通过`response.write()`方法将结果返回给客户端。
需要注意的是,这个示例只是演示了Hutool接收HTTP请求的基本流程,实际应用中还需要考虑请求的安全性、请求参数的验证、异常处理等问题。