2009-10-02 46 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无法实现这一点。