Java中的URL编码和解码特殊字符

16

在Java中,我需要使用HTTP Post向服务器发送请求,但如果URL参数包含某些特殊字符,则会抛出以下异常:

java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "&'"

用于发送数据的代码:

DefaultHttpClient httpclient = new DefaultHttpClient(); 
   HttpPost httpPost = new HttpPost(URL); 

   String sessionId = RequestUtil.getRequest().getSession().getId();
   String data = arg.getData().toString();

   List<NameValuePair> params = new ArrayList<NameValuePair>();   
   params.add(new BasicNameValuePair(param1, data));
   params.add(new BasicNameValuePair(param2, sessionId));
         httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));           

   HttpResponse response = (HttpResponse) httpclient.execute(httpPost);
在服务器端,我使用以下代码来读取信息
 String data = request.getParameter(param1);
   if (data != null) {
    actionArg = new ChannelArg(URLDecoder.decode(data, "UTF-8"));
   }

这段代码运行正确,但如果我输入一些特殊字符,比如 [aああ#$%&'(<>?/.,あああああ],它就会抛出异常。我想知道是否有人能够给我一些提示,让我能够编码和解码特殊字符?

非常感谢您提前的帮助。

4个回答

9

为了通过互联网安全传输文本:

import java.net.*;
...
try {
    encodedValue= URLEncoder.encode(rawValue, "UTF-8");
} catch (UnsupportedEncodingException uee) { }

并进行解码:

try {
    decodedValue = URLDecoder.decode(rawValue, "UTF-8");
} catch (UnsupportedEncodingException uee) { }

谢谢Steven,但正如你在我的代码中所看到的,我在客户端使用UrlEncodedFormEntity(params,“UTF-8”)对对象数据进行编码,而在服务器端,我使用URLDecoder.decode(data,“UTF-8”)进行解码。它能正确处理日文字符,但当我输入一些像[#$%&'(<>?/.,]这样的字符时,问题就出现了。 - Phu Nguyen

5

3
我监督了一些更好的解决方案。我们的Apache朋友们有StringEscapeUtils(org.apache.commons.lang.StringEscapeUtils)。如果可以的话,请检查一下它是否适用。 - uncaught_exceptions

3
String data = request.getParameter(param1);

如果这是 servlet API,那么参数已经被解码。不需要进一步处理百分号编码。
我没有使用过HttpClient,但请确保在标头中发送编码:
Content-type: application/x-www-form-urlencoded; charset=UTF-8

或者,如果必须的话,在任何 getParameter 调用之前设置已知编码:

request.setCharacterEncoding("UTF-8");

太棒了!非常感谢。 - jiantongc

1

尝试使用Guava

使用com.google.common.net.UrlEscapers

它可以很好地处理中文

就像这样:

Escaper escaper = UrlEscapers.urlFragmentEscaper();
String result = escaper.escape(yoururl);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接