记录解决java.io.IOException: Server returned HTTP response code: 500 for URL:xxxxxxxx

本文分享了在使用URLConnection进行POST请求时遇到HTTP 500错误的解决过程,详细记录了从本地测试、Linux云服务器到Windows Server的不同环境下的问题排查,最终通过使用OutputStreamWriter替代PrintWriter解决了编码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

踩坑经历

因为项目需要去对接别的接口,使用URLConnection POST请求https接口,发送json数组时遇到java.io.IOException: Server returned HTTP response code: 500 for URL。

当时情况是本地测试通过,正常返回,放到linux云服务器上测试通过,正常返回,放到windows server服务器上就有问题了,就是上面所说的。

根据报错分析首先联系接收方,发现对方没有报错内容,于是从自身找问题。首先想到是编码格式于是

尝试1

参考:https://blog.youkuaiyun.com/heweirun_2014/article/details/45535193

connection.setRequestProperty(“User-Agent”, “Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)”); 

最终没有解决问题

尝试2

conn.setRequestProperty("charsert", "utf-8");

最终没有解决问题

尝试3

参考:https://blog.youkuaiyun.com/maggiehexu/article/details/6448347

排除掉请求参数为空

最终没有解决问题

尝试4

out.println(param.getBytes("UTF-8"));

最终没有解决问题

尝试5

使用

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

out.write(param);

替换的

PrintWriter out = new PrintWriter(conn.getOutputStream()); // 用PrintWriter进行包装
out.println(param);

问题解决了!!!!!!!!一万头草泥马奔腾而过>_<

最后贴上代码希望对你有所帮助

 

   /** post请求 */
    public static String reqPost(String url, String param) throws IOException {
        String res = "";
        URLConnection conn = getConnection(url); // POST要求URL中不包含请求参数
        conn.setDoOutput(true); // 必须设置这两个请求属性为true,就表示默认使用POST发送
        conn.setDoInput(true);
        //conn.setRequestProperty("charsert", "utf-8");
        // 请求参数必须使用conn获取的OutputStream输出到请求体参数
        // 用PrintWriter进行包装
        /*PrintWriter out = new PrintWriter(conn.getOutputStream()); 
        out.println(param.getBytes("UTF-8"));*/
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
        out.write(param);
        out.flush(); // 立即充刷至请求体)PrintWriter默认先写在内存缓存中
        try// 发送正常的请求(获取资源)
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
        return res;
    }

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值