繁体   English   中英

BufferedReader UTF-8 BOM

[英]BufferedReader UTF-8 BOM

我在Java中有一个方法,尝试通过POST json请求获取一个整数(用户ID),这是该方法:

public static Integer getUserIdOwnerOfMsg(Message msg) {
        Integer idUser = null;
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("textMsg", msg.getTextMsg());
            jsonObject.put("hourMsg", msg.getHourMsg());

            List list = new LinkedList();
            list.addAll(Arrays.asList(jsonObject));
            String jsonString = list.toString();

            String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
            URL url = new URL(urlStr);

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "your user agent");
            con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
            //con.setRequestProperty("Content-Type", "text/html; charset=UTF-8");

            String urlParameters = "json=" + jsonString;

            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            InputStream instream;

            int status = con.getResponseCode();

            if (status != HttpURLConnection.HTTP_OK)
                instream = con.getErrorStream();
            else
                instream = con.getInputStream();

            BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // ISO-8859-1
            in.mark(1);
            if(in.read() != 0xFEFF)
                in.reset();
            String inputLine;
            StringBuilder response = new StringBuilder();

            while((inputLine = in.readLine()) != null)
                response.append(inputLine);

            in.close();

            JSONObject object = new JSONObject(response.toString());
            Boolean correct = object.getBoolean("correct");
            if (correct) {
                idUser = object.getInt("id");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  idUser;
    }

问题是响应包含一个UTF-8 BOM字符,邮递员的结果还可以,我可以看到id:( {"id":"7","correct":true}

邮差

但是在android studio上调试时, idUser的值为""null ,我不知道为什么,我尝试了很多方法来解决此问题而没有成功。

同样在php服务器端,我执行了echo mb_detect_encoding($idUsuario); 并且我得到了ASCII编码,以防可能找到解决方案。

任何帮助将不胜感激,谢谢!

所以最后我得到了解决方案,我把它发布在这里,以防有人和我有同样的问题,问题出在JSON的参数上,因为它们包括UTF-8字符(例如 ,所以不要读取这样的参数:

wr.writeBytes (urlParameters);

我必须这样做:

byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);

如果有人需要,我还会发布完整的功能:

public static Integer getUserIdOwnerOfMsg(Message msg) {
    Integer idUser = null;
    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("textMsg", msg.getTextMsg());
        jsonObject.put("hourMsg", msg.getHourMsg());

        List list = new LinkedList();
        list.addAll(Arrays.asList(jsonObject));
        String jsonString = list.toString();

        String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
        URL url = new URL(urlStr);

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "your user agent");
        con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");

        String urlParameters = "json=" + jsonString;

        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream (con.getOutputStream());
        byte[] buf = urlParameters.getBytes("UTF-8");
        wr.write(buf, 0, buf.length);
        wr.flush();
        wr.close();

        InputStream instream;

        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK)
            instream = con.getErrorStream();
        else
            instream = con.getInputStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")),8192);
        String inputLine;
        StringBuilder response = new StringBuilder();

        while((inputLine = in.readLine()) != null)
            response.append(inputLine);

        JSONObject object = new JSONObject(response.toString());
        Boolean correct = object.getBoolean("correct");
        if (correct) {
            try {
                String idUserText = object.getString("id");
                idUser = Integer.valueOf(idUserText);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        in.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  idUser;
}

仅此而已,祝您编程愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM