跟进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);
}
答案 0 :(得分:0)
使用TextView而不是WebView修复了问题