處理異常Could not read document: Invalid UTF-8 start byte 0xb2\n...備忘

首先先把異常貼出來:

{"success":false,"code":500,"msg":"服務器異常:Could not read document: Invalid UTF-8 start byte 0xb2\n at [Source: java.io.PushbackInputStream@ed71aaf7; line: 1, column: 94] (through reference chain: com.icss.sms.badSupplier.pojo.OdsTBlgysBadSuppInfoByInterList[\"obsi\"]->com.
icss.sms.badSupplier.pojo.OdsTBlgysBadSuppInfoByInter[\"orgName\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xb
2\n at [Source: java.io.PushbackInputStream@ed71aaf7; line: 1, column: 94] (through reference chain: com.icss.sms.badSupplier.pojo.OdsTBlgysBadSuppInfoByInterList[\"obsi\
"]->com.icss.sms.badSupplier.pojo.OdsTBlgysBadSuppInfoByInter[\"orgName\"])","bean":null,"data":null,"footer":null,"count":null,"page":null,"limit":null}

此異常是與第三方公司對接接口我方後臺Java模擬發送Ajax請求時,對方返回的異常信息。

發送請求包裝類的詳細代碼如下

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    /**
     * 向指定 URL 發送POST方法的請求
     *
     * @param url
     *            發送請求的 URL
     * @param param
     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
     * @return 所代表遠程資源的響應結果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
       try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 發送請求參數
            out.print(param);
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
           }
        } catch (Exception e) {
            System.out.println("發送 POST 請求出現異常!" + e);
            e.printStackTrace();
        }
        // 使用finally塊來關閉輸出流、輸入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}

調用代碼:

//param數據結構大致爲{data:[name: "", sex:""]}
Gson gson = new Gson();
System.out.println(gson.toJson(param));
String json = gson.toJson(param);
String res = http.sendPost("http://10.1.10.106:9080/sms-web/service/odsTBlgysBadSuppInfo/badSupAll",json);

結果就返回文章開頭的異常。隨後在調用發送請求時對參數字符串重新進行編碼

byte[] utf8JsonString = json.getBytes("UTF8");
String str = new String(utf8JsonString, "UTF8");
String res = http.sendPost("http://10.1.10.106:9080/sms-web/service/odsTBlgysBadSuppInfo/badSupAll",str);

結果還是報錯。然後在網上查詢相關資料,發現在發送請求時的寫法應該爲

URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("contentType", "UTF-8");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 發送請求參數
out.write(param);
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));

指定一下輸出流的字節編碼格式爲UTF-8,即可解決。

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

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