tags:

views:

382

answers:

2

hi all,

I use the below code to send data to a servlet: When encoding = "UTF-8" or "GBK", the data is received correctly. But when encoding = "UTF-16", The receiver receives null. WHY??

The Sender:

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

The receiver servlet:

            log.info(request.getParameter("notify_type"));    //print null
+1  A: 

You have 2 issues,

  1. UTF-16 is not supported by lots of web servers. Some URLDecoder can only handle single byte encoding (ASCII, Latin-1) and UTF-8.
  2. You are using mixed encoding if your default encoding is not UTF-16. UTF-8 and GBK are both ASCII compatible (ASCII is encoded as itself) so you can mix with ASCII but you can't do that with UTF-16.
ZZ Coder
+1  A: 

According to the Javadocs for URLEncoder, you should only use UTF-8 because other encodings may cause problems. They link directly to the W3C spec from the Javadocs.

Asaph