【问题标题】:Android: Fails to decode UTF-8Android:无法解码 UTF-8
【发布时间】:2015-07-19 18:47:31
【问题描述】:

关注this

我正在通过 TCP 套接字向 Android 发送 UTF-8 编码的字符串。

我在 python 端将其编码为 utf-8,然后在发送前转换为 Base64。

在接收端,然后我从 Base64 解码并解码 UTF-8。

然后我将它传递给一个 WebView 并显示它,但输出与输入不匹配。

有时我也会得到随机的东西。我认为这与我在发送“UTF-8”字符串之前的握手有关。

    es = Elasticsearch()
    #receive query from the client
    query = self.request.recv(1024)
    #Cut off the characters that aren't recognized
    query=query[2:]
    #for testing
    query=query.lower().strip().replace(' ','_')
    print query
    #Send response that query was received
    self.request.send("200...OK\n")
    #cur_thread = threading.current_thread()
    #response = "{}: {}".format(cur_thread.name, query)
    res = es.search(index="painter",body={"query": { "match" : {"title" : query}},"size":1  })
    if res['hits']['hits']:
        response = res['hits']['hits'][0]['_source']['text']
        self.request.send("201...RE\n")

    response=response.encode('utf-8')
    encoded=binascii.b2a_base64(response)

    self.request.sendall(encoded)

如您所见,我在发送编码字符串之前发送了“200...OK\n”和“201...RE\n”。

在 Android 端:

 TextIn = getResponse(dataInputStream);
            if (TextIn!=null)
            {
                if (TextIn.equals("200...OK")){
                    publishProgress("Query Sent!");
                    TextIn=getResponse(dataInputStream);
                    Log.d("TEXTIN",TextIn);
                    if(TextIn.equals("201...RE")){
                        returnvalue=convertStreamToString(dataInputStream);
                    }
                    else{
                        returnvalue="FAILURE";
                    }

                }
            }

接收“200..OK”和“201..RE:”的函数:

        private String getResponse(InputStream is){
        String line="";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is),8);
        try{
            line=rd.readLine();
        }
        catch (Exception e){
            Toast.makeText(MainActivity.this, "Stream Exception", Toast.LENGTH_SHORT).show();
        }
        return line;
        }

接收'UTF-8'数据的函数:

    private String convertStreamToString(InputStream is) {
        BufferedInputStream bi = new BufferedInputStream(is);
        byte[] b = new byte[1024];
        byte[] temp;

        ByteArrayOutputStream fold=new ByteArrayOutputStream();
        try {
            while (bi.read(b,0,1024)!=-1)
            {
                fold.write(b);
               // Log.d("TOTAL",decodeUTF8(b));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        temp=fold.toByteArray();
        temp= Base64.decode(temp,Base64.DEFAULT);
        return decodeUTF8(temp).toString();
    }

解码

    private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
String decodeUTF8(byte[] bytes) {
    return new String(bytes, UTF8_CHARSET);
}

【问题讨论】:

    标签: android python encoding utf-8


    【解决方案1】:

    使用 TextView 而不是 WebView 解决了问题

    【讨论】:

      猜你喜欢
      • 2011-01-01
      • 2021-03-22
      • 2018-04-22
      • 1970-01-01
      • 2021-05-14
      • 2020-07-17
      • 2018-05-05
      • 2019-11-10
      • 1970-01-01
      相关资源
      最近更新 更多