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

踩坑经历

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

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

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

尝试1

参考:https://blog.csdn.net/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.csdn.net/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;
    }

 

 

posted @ 2019-11-14 10:03  宝贝企鹅  阅读(11513)  评论(0编辑  收藏  举报