2016-10-28 87 views
0

我正在開發帶有後端的android應用程序,均在Java中,並通過Http Post進行通信。 當我發送包含非英文字符的請求時,後端可以很好地處理它們,但是當後端嘗試返回非英文字符時,它們會收到'?'。 說我送的parmas "STR=שלום עולם"(希伯來文字符)從Http Post接收UTF-8響應

後端servlet示例:

public class DebugServlet extends HttpServlet { 
    @Override 
    public void doPost(HttpServletRequest req, HttpServletResponse resp) 
     throws IOException { 

     String param = req.getParameter("STR"); 

     log(param); //Prints שלום עולם, So receiving fine! 

     try(PrintWriter out = resp.getWriter()) { 
      out.print(param); 
     } 
    } 
} 

客戶端代碼:

private final static String CHARSET = "UTF-8"; 
public static void send(String server, String servletName, Map<String, String> params){ 
    try{ 
     URL url = new URL(server + servletName); 
     URLConnection connection = url.openConnection(); 

     HttpURLConnection conn = (HttpURLConnection) connection; 

     OutputStream os; 

     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); 
     conn.setRequestMethod("POST"); 
     conn.setUseCaches(false); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 
     os = conn.getOutputStream(); 

     //Add parameters 
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, CHARSET)); 
     StringBuilder paramsSB = new StringBuilder(); 
     boolean isFirst = true; 
     for(Map.Entry<String,String> entry : params.entrySet()){ 
      if(isFirst) 
       isFirst = false; 
      else 
       paramsSB.append("&"); 
      paramsSB.append(URLEncoder.encode(entry.getKey(), CHARSET)); 
      paramsSB.append("="); 
      paramsSB.append(URLEncoder.encode(entry.getValue(), CHARSET)); 
     } 

     writer.append(paramsSB.toString()); 

     writer.flush(); 
     writer.close(); 
     os.close(); 

     int responseCode; 
     responseCode = conn.getResponseCode(); 

     if (responseCode != 200) 
      throw new RuntimeException("..."); 

     StringBuilder chain = new StringBuilder(""); 
     try(BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { 
      String line = ""; 
      while ((line = rd.readLine()) != null) { 
       chain.append(line); 
      } 
     } 

     Log.d("MyTAG", chain.toString()); //Prints "???? ????", that's the problem 
    } catch (IOException e) { 
     // writing exception to log 
     throw new RuntimeException("..."); 
    } 
} 

謝謝:)

回答

2

您需要設置響應爲HttpServletResponse編碼UTF-8。默認編碼是ISO_8859_1

// response.setContentType("text/plain"); 
    response.setCharacterEncoding("UTF-8"; 

    // Write utf-8 strings