java 发送 Http 请求笔记 以及踩得坑

这篇博客记录了作者在使用Java发送HTTP请求时遇到的问题及解决方案。主要讨论了如何通过HttpServletRequest获取参数,指出getInputStream和getParameter的关系,强调了流只能使用一次。推荐使用Apache HttpClient库进行POST请求,并分享了因Content-Type设置不正确导致的接收数据失败的教训。
摘要由CSDN通过智能技术生成

java 发送 Http 请求笔记

http 代码

这几天使用 java 代码发送 http请求, 真的是搞得我焦头烂额. 在网上找了几十篇文档, 几乎都大同小异.

首先是网络上最通用的代码

    public static void callUrl(@NonNull String json, @NonNull String url, Charset charset) throws IOException {
   
        // 请求url
        log.info("send json: {}", json);
        URL postUrl = new URL(url);

        log.info(charset.name());
        json = URLEncoder.encode(json, charset.name());
        // json = new String(json.getBytes(charset.name()), charset.name());

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");    // 默认是 GET方式
        connection.setUseCaches(false);         // Post 请求不能使用缓存
        connection.setInstanceFollowRedirects(true);   //设置本次连接是否自动重定向
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.addRequestProperty("Connection", "Keep-Alive");//设置与服务器保持连接
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;0.9");

        // 连接
        connection.connect();
        try (DataOutputStream out = 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逆光影者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值