Android: 无法解码 UTF-8
Android: Fails to decode UTF-8
跟进 this
我正在通过 TCP 套接字将 UTF-8 编码的字符串发送到 Android。
我在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);
}
使用 TextView 而不是 WebView 解决了问题
跟进 this
我正在通过 TCP 套接字将 UTF-8 编码的字符串发送到 Android。
我在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);
}
使用 TextView 而不是 WebView 解决了问题