2014-04-04 52 views
1

我使用nodejs作爲服務器和java(android)作爲客戶端,我成功地通過發佈數據從android到節點。但我的問題時,Android的發送數據(串)由空間新線(輸入)其收到的節點,但性格在變化,通過帖子從android發送數據到node.js?

例如,我在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

你檢查值在「文字」中?它的價值是什麼? – Sree

+0

是的,我做的,價值是你好%0AI +學習+機器人,因爲我編碼文本到UTF – ltvie

+0

你需要res.on(「數據」... –

回答

2

該字符串是URL編碼的,正如您在代碼中明確要求的(並且需要定期POST)。在服務器上解碼它。

要在服務器端進行解碼,這樣做:

var querystring = require('querystring'); 
querystring.unescape(data.replace(/\+/g, " ")); 
+0

如何在服務器解碼?我已經嘗試使用手動代碼使用如果你想要使用Node.js,你可以使用下面的代碼:text.replace(/ + /,「」)它不起作用 – ltvie

+0

Node.js有一個內建函數來做到這一點 嘗試 'var querystring = require('querystring');' 'querystring.unescape數據);' – FMontano

+0

@FMontano:我嘗試和工作在某些情況下,只有新行(輸入)工作,但空間仍然是「+」不是「」 – ltvie

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(); 
     }