java 发送 http 请求练习两年半(HttpURLConnection)

这篇具有很好参考价值的文章主要介绍了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 转对象封装 没对上。文章来源地址https://www.toymoban.com/news/detail-420977.html

到了这里,关于java 发送 http 请求练习两年半(HttpURLConnection)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 一个 TCP 连接可以发送多少个 HTTP 请求

    一个 TCP 连接可以发送多少个 HTTP 请求

    第一个问题 第二个问题 第三个问题 第四个问题 第五个问题 曾经有这么一道面试题:从 URL 在浏览器被被输入到页面展现的过程中发生了什么? 相信大多数准备过的同学都能回答出来,但是如果继续问:收到的 HTML 如果包含几十个图片标签,这些图片是以什么方式、什么顺

    2024年02月08日
    浏览(11)
  • java发送Http请求

    使用java 11添加的HttpClient新API发送Http(Https)请求 HTTP客户端是在Java 11中添加的。它可以用于通过网络请求HTTP资源。它支持 HTTP / 1.1和HTTP / 2(同步和异步编程模型),将请求和响应主体作为反应流处理,并遵循熟悉的构建器模式。 参考文章:https://blog.csdn.net/allway2/article/detail

    2023年04月12日
    浏览(10)
  • 用java发送http请求

    在 Java 中发送 HTTP 请求可以使用标准的 Java 库或者第三方库。这里介绍使用 Java 标准库中的 HttpURLConnection 类来发送 HTTP 请求的方法: 首先,使用 URL 类来创建一个 URL 对象,指定要访问的 URL。 使用 URL 对象的 openConnection 方法来获取 HttpURLConnection 对象。 设置 HTTP 请求的方法

    2024年02月16日
    浏览(10)
  • Java发送HTTP GET/POST请求

    在这篇文章中,将向你展示四种发送Http的GET/POST的例子,如下: 在Java11的java.net.http.*包中,有一个HttpClient类可以完成HTTP请求。 Java11HttpClientExample.java 本例使用HttpURLConnection(http)和HttpsURLConnection(https) HttpURLConnectionExample.java 使用Apache HttpClient完成HTTP请求的发送需要添加Maven依赖

    2024年02月13日
    浏览(13)
  • Java 发送Http请求携带中文参数时 请求报400的错误请求

    在 Java 中,URL 中不能直接包含中文字符,因为 URL 规范要求 URL 必须是 ASCII 字符。如果需要在 URL 中传递中文参数,需要对中文参数进行 URL 编码,将其转换为浏览器中的参数形式。可以使用 java.net.URLEncoder 类来进行 URL 编码。

    2024年02月11日
    浏览(9)
  • 【Java】汇总Java中发送HTTP请求的7种方式

    【Java】汇总Java中发送HTTP请求的7种方式

    今天在项目中发现一个功能模块是额外调用的外部服务,其采用CloseableHttpClient调用外部url中的接口…… CloseableHttpClient HTTP发送请求处理流程:

    2024年02月11日
    浏览(11)
  • java http get post 和 发送json数据请求

    java http get post 和 发送json数据请求

    浏览器请求效果       main调用  

    2024年02月16日
    浏览(18)
  • java业务代码发送http请求(Post方式:请求参数为JSON格式;Get方式)

    实际开发中,可能需要发送http请求到第三方服务获取数据,于是就有以下应用: 依赖: 假设我需要在我的业务代码中调用该地址: url:http://xx.xx:xxxx/user/count 请求方法:post 内容类型:application/json 请求参数:id, username 返回参数:code 响应结果 int类型                  

    2024年02月12日
    浏览(17)
  • java使用hutool工具类发送http或者https请求太香啦

    我们使用java内置的http工具实现远程调用的时候,都是用try catch包一堆代码,巨难受,今天看见有人使用hutool工具类那是天简单了呀,具体操作如下: 1,引入依赖 2, 如果不需要设置其他什么头信息,代码: 如果是https请求直接换url里面的http就行 返回信息格式: {\\\"code\\\":200

    2024年02月14日
    浏览(11)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包