2009-10-02 67 views
1

我使用下面的代碼發送數據到一個servlet: 當encoding =「UTF-8」或「GBK」時,數據被正確接收。 但是,當encoding =「UTF-16」時,接收器接收到null。爲什麼??URL參數編碼/接收問題

發件人:

URL url = new URL(notifyURL); 
    HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
    connection.setDoOutput(true); 
    connection.setRequestMethod("POST"); 
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);   
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); 
    out.write("notify_id=" + URLEncoder.encode("123", encoding) + "&notify_type=" + URLEncoder.encode("any", encoding)); 
    out.flush(); 
    out.close(); 
    connection.connect(); 

接收器的servlet:

  log.info(request.getParameter("notify_type")); //print null 

回答

1

根據Javadocs的URLEncoder,您應該只使用UTF-8,因爲其他編碼可能會導致問題。它們直接鏈接到Javadocs的W3C規範。

1

你有2個問題,

  1. UTF-16不是由大量Web服務器的支持。有些URLDecoder只能處理單字節編碼(ASCII,Latin-1)和UTF-8。
  2. 如果默認編碼不是UTF-16,則使用混合編碼。 UTF-8和GBK都兼容ASCII(ASCII編碼爲自身),因此您可以與ASCII混合使用,但UTF-16無法實現這一點。