java 发送 http 请求练习两年半(HttpURLConnection)
1、起一个 springboot 程序做 http 测试:
@GetMapping("/http/get")
public ResponseEntity<String> testHttpGet(@RequestParam("param") String param) {
System.out.println(param);
return ResponseEntity.ok("---------> revive http get request --------->");
}
@PostMapping("/http/post")
public ResponseEntity<String> testHttpPost(@RequestBody List<Object> body) {
System.out.println(body);
return ResponseEntity.ok("---------> receive http post request --------->");
}
2、写一个 HttpURLConnection 自定义客户端
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; public class MyHttpClient { private final HttpURLConnection connection; private MyHttpClient(String url, Map<String, String> params) throws IOException {
connection = buildConnection(url, params);
} private MyHttpClient(String url, Map<String, String> params, String jsonBody) throws IOException {
connection = buildConnection(url, params);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.writeBytes(jsonBody);
outputStream.flush();
}
} public static MyHttpClient get(String url, Map<String, String> params) throws IOException {
return new MyHttpClient(url, params);
} public static MyHttpClient post(String url, Map<String, String> params, String jsonBody) throws IOException {
return new MyHttpClient(url, params, jsonBody);
} /**
* 创建 http 连接
*
* @param url 请求路径
* @param params 请求参数,可以为空
* @return http 连接
*/
private HttpURLConnection buildConnection(String url, Map<String, String> params) throws IOException {
String requestParams = getParamsString(params);
return (HttpURLConnection) new URL(requestParams != null ? url + "?" + requestParams : url).openConnection();
} /**
* 获取 http 请求响应结果
*
* @return 响应结果,失败抛异常
*/
public String getResponse() throws IOException {
int responseCode = connection.getResponseCode();
if (responseCode >= HttpURLConnection.HTTP_OK && responseCode < HttpURLConnection.HTTP_MULT_CHOICE) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
} in.close(); connection.disconnect();
return response.toString();
} else {
connection.disconnect();
InputStream errorStream = connection.getErrorStream();
if (errorStream == null) {
throw new ConnectException("request fail");
}
throw new ConnectException(new String(errorStream.readAllBytes(), StandardCharsets.UTF_8));
}
} /**
* 拼接请求参数
*
* @param params 参数 map
* @return 请求参数字符串
*/
public static String getParamsString(Map<String, String> params) {
if (params == null || params.isEmpty()) {
return null;
} StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
result.append("&");
} String resultString = result.toString();
return resultString.length() > 0
? resultString.substring(0, resultString.length() - 1)
: resultString;
}
}
3、测试 get 和 post 请求
public static void main(String[] args) throws IOException {
MyHttpClient myHttpClient = MyHttpClient.get("http://127.0.0.1:8083/springboot/http/get",
Map.of("param", "1"));
String resultGet = myHttpClient.getResponse();
System.out.println(resultGet);
MyHttpClient httpClient = MyHttpClient.post("http://127.0.0.1:8083/springboot/http/post",
null,
"[1,2,3,4,5]");
String resultPost = httpClient.getResponse();
System.out.println(resultPost);
}
4、控制台输出结果
---------> revive http get request --------->
---------> receive http post request ---------> Process finished with exit code 0
中间遇到一些坑,经常以为 http 会有方法像 openfeign 那样传入请求参数,忽略了路径拼接,
启动的 springboot 接收的 post 的请求体为 List 类型,且 Content-Type 是 json,在测试 post 请求时一直报错,看了 spring 控制台才发现 json 转对象封装 没对上。
java 发送 http 请求练习两年半(HttpURLConnection)的更多相关文章
- Java发送HTTPS请求
前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...
- 使用Java发送Http请求的内容
公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...
- Java发送Http请求并获取状态码
通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...
- 通过java发送http请求
通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...
- 编写爬虫(spider)的预备知识:用java发送HTTP请求
使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...
- JAVA发送HttpClient请求及接收请求结果
1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...
- (转)Java发送http请求(get 与post方法请求)
本文转载于:http://bijian1013.iteye.com/blog/2166855 package com.bijian.study; import java.io.BufferedRead ...
- Java 发送 Https 请求工具类 (兼容http)
依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...
- Java发送socket请求的工具
package com.tech.jin.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import ...
- Java发送Http请求
package com.liuyu.test; import java.io.BufferedReader; import java.io.IOException; import java.io.In ...
随机推荐
- Python脚本的输入输出
一.必备知识回顾和补充 1. Hello world回顾 1.输出文本,使用print函数输出文本. 2.让用户输入名字,然后输出带名字的问候语.使用input函数获取用户的输入,使用变量保存输入值. ...
- java 注解结合 spring aop 实现自动输出日志
auto-log auto-log 是一款为 java 设计的自动日志监控框架. 创作目的 经常会写一些工具,有时候手动加一些日志很麻烦,引入 spring 又过于大材小用. 所以希望从从简到繁实现一 ...
- Git Conventional Commits (Git代码提交说明规范)
Conventional Commits (代码提交说明规范) Conventional Commits 是关于Git Commit 提交代码时, 填写的说明文字的一个规范. 这个规范提供了一套易于理 ...
- Ubuntu20.04下的ESP8266环境
硬件说明 ESP8266使用的是3.3V供电, 和Arduino不一样, ESP8266的I/O脚是不能防5V的, 连上就烧. 其输出只有12mA, 而Arduino是20-40mA. ESP8266 ...
- 通过performance_schema获取造成死锁的事务语句(转)
数据库日常维护中我们经常遇到死锁的问题,由于无法获取造成死锁的事务内执行过的语句,对我们死锁的分析造成很大的困难.但是在MySQL 5.7中我们可以利用performance_schema来获取这些语 ...
- 获取Linux mac地址(centos与ubuntu通用)
ip -a addr| grep link/ether | awk '{print $2}'| head -n 1 获取Linux mac地址(centos与ubuntu通用)
- 初级算法 - C++反转链表
顾名思义, 就是将链表的所有结点反转. 解释见:[剑指offer]反转链表,C++实现(链表) 代码: #include <iostream> struct NodeList { int ...
- Qt开发技术:QtCharts(一)QtCharts基本介绍以及图表框架详解
若该文为原创文章,未经允许不得转载原博主博客地址:https://blog.csdn.net/qq21497936原博主博客导航:https://blog.csdn.net/qq21497936/ar ...
- Celery异步处理任务时遇到的错误ValueError: not enough values to unpack (expected 3, got 0)
开启celery异步,终端命令: celery -A celery_tasks.main worker -l info 如果上面运行后,发送短信码的时候没有报如下错误: ValueError: not ...
- 对于Celery原理的简单理解
参考博客: https://www.cnblogs.com/forward-wang/p/5970806.html https://blog.csdn.net/cuomer/article/detai ...