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)的更多相关文章

  1. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  2. 使用Java发送Http请求的内容

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...

  3. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  4. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  5. 编写爬虫(spider)的预备知识:用java发送HTTP请求

    使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...

  6. 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 ...

  7. (转)Java发送http请求(get 与post方法请求)

    本文转载于:http://bijian1013.iteye.com/blog/2166855 package com.bijian.study; import java.io.BufferedRead ...

  8. Java 发送 Https 请求工具类 (兼容http)

    依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...

  9. Java发送socket请求的工具

    package com.tech.jin.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import ...

  10. Java发送Http请求

    package com.liuyu.test; import java.io.BufferedReader; import java.io.IOException; import java.io.In ...

随机推荐

  1. NC51222 Strategic game

    题目链接 题目 题目描述 Bob enjoys playing computer games, especially strategic games, but sometimes he cannot ...

  2. MOS 管工作原理

    浅谈MOS管的工作原理_数字IC修行者的博客-CSDN博客_mos管工作原理 一文讲明白MOS管工作原理 - 知乎 (zhihu.com) 闪存基本原理 (sohu.com)

  3. MySQL查看bin_log日志

    有这样一段业务逻辑,首先保存业务数据,然后发送报文,最后确认报文回来以后更新业务数据.伪代码大概是这样的: /** * 保存数据,并调用发送报文方法 */ public void save() { / ...

  4. OCR 02: Tesseract-OCR

    Catalog OCR 01: EasyOCR OCR 02: Tesseract-OCR OCR 03: PaddleOCR Project Host And Brief Official Site ...

  5. VMWare“Could not get vmci driver version:句柄无效”的错误

    这几天都不顺,从周一接手数据仓库的事,本来以为很简单,很快都能搞定,结果搞了一天没搞定,主要原因,自己觉得是系统底层搭建缺失个别库文件, 想换一个高一点版本的虚拟系统centos6.2结果又把虚拟机搞 ...

  6. ubuntu16.04 ssh启用root连接

    安装好ubuntu16.04 server版默认是不允许客户端ssh工具连接root的. 启用方法如下: 1.设置root密码 dylan@ubuntu:~$ sudo passwd root [su ...

  7. pycharm—flask创建简单web项目

    1.系统 系统 版本 OS win 10 pycharm 专业版2022.3.1 2.引入flask包 pip install flask 3.项目目录展示.代码.浏览器访问 from flask i ...

  8. 解密prompt系列24. RLHF新方案之训练策略:SLiC-HF & DPO & RRHF & RSO

    去年我们梳理过OpenAI,Anthropic和DeepMind出品的经典RLHF论文.今年我们会针对经典RLHF算法存在的不稳定,成本高,效率低等问题讨论一些新的方案.不熟悉RLHF的同学建议先看这 ...

  9. 树莓派/Linux ubuntu 开机自动改网络mac地址(主要适用于拷贝内存卡的情况/不同树莓派mac地址不同)

    树莓派/Linux ubuntu 开机自动改网络mac地址(主要适用于拷贝内存卡的情况/不同树莓派mac地址不同) yaml文件名根据自己原卡中名字更改 address=$(cat /sys/clas ...

  10. 实操开源版全栈测试工具RunnerGo安装(三)MacOS安装

    以Sonoma 14.1.2系统为例 视频教程:https://www.bilibili.com/video/BV1fG411e7h2/?spm_id_from=333.999.0.0 1.下载并安装 ...