【问题标题】:BufferedReader UTF-8 BOMBufferedReader UTF-8 BOM
【发布时间】:2018-10-28 07:23:00
【问题描述】:

我在 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 编码,以防万一有助于找到解决方案。

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

【问题讨论】:

  • UTF8 永远不需要 BOM,PHP 也不关心编码。您的文本编辑器可能会在打开 <?php 之前将其添加到您的一个或多个 PHP 源文件中。

标签: php encoding byte-order-mark


【解决方案1】:

所以最后我得到了解决方案,我把它贴在这里以防万一有人和我有同样的问题,问题出在 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;
}

就是这样,编码愉快!

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2011-07-21
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2012-02-12
    • 2016-05-04
    相关资源
    最近更新 更多