記錄解決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;
    }

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章