酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

揭秘Hutool发送HTTPS请求的方法及示例代码

Hutool提供了一个HTTP工具类`HttpUtil`,你可以使用其中的`post()`或`postJson()`方法来发送HTTPS请求。例如: ```java import cn.hutool.http.HttpMethod; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; public class Main { public static void main(String[] args) { // 发送POST请求 HttpRequest request = HttpRequest.post("https://example.com/api"); request.header("Content-Type", "application/json"); request.param("key", "value"); // 设置参数 HttpResponse response = HttpUtil.execute(request); System.out.println(response.bodyString()); // 打印响应内容 } } ``` 如果你需要发送JSON数据,可以使用`postJson()`方法: ```java import cn.hutool.json.JSONObject; import cn.hutool.http.HttpMethod; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; public class Main { public static void main(String[] args) { // 发送POST请求并携带JSON数据 JSONObject json = new JSONObject(); json.put("key", "value"); HttpRequest request = HttpRequest.post("https://example.com/api") .json(json.toJSONString()); HttpResponse response = HttpUtil.execute(request); System.out.println(response.bodyString()); // 打印响应内容 } } ``` 注意:在实际使用中,你可能需要处理可能出现的异常,如网络问题、服务器返回的状态码等。 ######[AI写代码神器 | 316点数解答 | 2024-04-23 09:05:50]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]