我使用nodejs作为服务器,使用java(android)作为客户端,我通过post从android发送数据到节点。但我的问题是当android发送数据(字符串)由空间和新行(输入)组成时,它在节点上收到但字符已更改,
例如,我从android
发送此字符串Hello
I learn android
字符串发送到节点并收到,但我在节点
中得到了这个Hello%0AI+learn+android
我使用此代码将字符串发送到android中的节点。
public void btnOnClick(){
String text= URLEncoder.encode(editText.getText().toString(), "utf-8"); //I get from editText and convert to utf-8
sendToNode(text);
}
public void sendToNode(String text){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myDomain.com:8888/");
UrlEncodedFormEntity form;
try {
Log.i("kirim ke node isitextAsli ",text);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("datanah",text));
form=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
httppost.setEntity(form);
HttpResponse response = httpclient.execute(httppost);
Log.i("HTTP Post", "Response from server node = " + response.getStatusLine().getReasonPhrase() + " Code = " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
Log.e("HTTP Post", "Protocol error = " + e.toString());
} catch (IOException e) {
Log.e("HTTP Post", "IO error = " + e.toString());
}
}
我将此代码用于节点
中的接收字符串req.addListener('data', function(chunk) { data += chunk; });
req.addListener('end', function() {
console.log("from android :"+data); //result of data is Hello%0AI+learn+android
});
我如何解决我的问题?
请帮助,谢谢。
答案 0 :(得分:3)
字符串是URL编码的,正如您在代码中明确要求的那样(需要常规POST)。在服务器上解码它。
要在服务器端对其进行解码,请执行以下操作:
var querystring = require('querystring');
querystring.unescape(data.replace(/\+/g, " "));
答案 1 :(得分:0)
以下是编码和解码的示例,您希望在服务器部分解码
String encoded;
try {
encoded = URLEncoder.encode(input, "UTF-8");
System.out.println("URL-encoded by client with UTF-8: " + encoded);
String incorrectDecoded = URLDecoder.decode(encoded, "ISO-8859-1");
System.out.println("Then URL-decoded by server with ISO-8859-1: " + incorrectDecoded);
String correctDecoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Server should URL-decode with UTF-8: " + correctDecoded);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}