2014-09-02 34 views
0

我看到這篇文章How to send unicode characters in an HttpPost on Android,但我通常以這種方式在AsyncTask類中請求。我的日誌也在urlParameters中打印本地語言,但服務器在完美時返回沒有結果對於英語字符串:如何從http發送請求中的Unicode字符asyncTask

@Override 
protected String doInBackground(String... URLs) { 

    StringBuffer response = new StringBuffer(); 

    try { 
     URL obj = new URL(URLs[0]); 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
     // add request header 
     con.setRequestMethod("POST"); 

     if (URLs[0].equals(URLHelper.get_preleases)) { 
      urlCall = 1; 
     } else 
      urlCall = 2; 

     // String urlParameters = "longitude=" + longitude + "&latitude="+latitude; 

     // Send post request 
     con.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 

     wr.writeBytes(urlParameters); 
     wr.flush(); 
     wr.close(); 

     int responseCode = con.getResponseCode(); 
     if (responseCode == 200) { 
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
      String inputLine; 

      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 
      in.close(); 
     } 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return response.toString(); 
} 

有沒有一種方法來設置字符集UTF-8請求參數編碼這種方式?

+0

[how-to-send-unicode-characters-in-an-httppost-on-android](http://stackoverflow.com/questions/5084462/how-to-send-unicode-characters-in-an -httppost-on-android) – SilentKiller 2014-09-02 04:44:05

+0

@SilentKiller多數民衆贊成在他發佈的問題:) – KOTIOS 2014-09-02 04:48:17

+0

@DIVA請檢查此行是否在上面的代碼可用'StringEntity stringEntity = new StringEntity(msg,「UTF-8」);'他不在任何地方提供charSet。 – SilentKiller 2014-09-02 04:49:37

回答

1

String urlParameters =「longitude =」+ longitude +「& latitude =」+ latitude;

您需要對注入到application/x-www-form-urlencoded上下文中的組件進行URL編碼。 (即使拋開非ASCII字符,如通過符號,否則將中斷。)

指定您正在使用在調用你的要求的字符串到字節編碼,例如:

String urlParameters = "longitude=" + URLEncoder.encode(longitude, "UTF-8")... 

...

DataOutputStream wr = new DataOutputStream(con.getOutputStream());

A DataOutputStream用於向下發送類似結構的Java類型的二進制數據。它不會給你寫任何HTTP請求體所需的東西。也許你的意思是OutputStreamWriter

但既然你已經有了字符串全部在內存中,你可以簡單地做:

con.getOutputStream().write(urlParameters.getBytes("UTF-8")) 

(注意UTF-8這裏是有點多餘的,因爲您已經將URL編碼的所有非ASCII字符轉換爲。 %xx逃逸,會有什麼爲UTF-8編碼的。但是一般它幾乎總是最好指定比省略,並恢復到不可靠的系統默認編碼特定編碼。)

新的InputStreamReader(CON .getInputStream())

也省略了編碼並恢復爲可能不是響應編碼的默認編碼。所以你可能會發現在響應中非ASCII字符也會被錯誤地讀取。

+0

正是我需要的,以滿足我的截止日期謝謝你 – 2014-09-02 08:49:34