处理异常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");

你可能感兴趣的:(Java,Ajax)