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

Phu*_*yen 16 java urlencode

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

java.lang.IllegalArgumentException:URLDecoder:转义(%)模式中的非法十六进制字符 - 对于输入字符串:"&'"

发送数据的代码

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);
Run Code Online (Sandbox Code Playgroud)

在服务器端,我使用以下代码来读取信息

 String data = request.getParameter(param1);
   if (data != null) {
    actionArg = new ChannelArg(URLDecoder.decode(data, "UTF-8"));
   }
Run Code Online (Sandbox Code Playgroud)

代码工作正常,但如果我输入一些特殊的字符,如[aああ#$%&'(<>?/.,あああああ],它将抛出异常.我想知道是否有人可以帮助我一些提示能够编码并解码特殊字符?

非常感谢你提前.

Ste*_*ven 9

编码文本以便安全通过互联网:

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

并解码:

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


unc*_*ons 5

遗憾的是,url编码器无法解决您的问题.我有这个问题,并使用自定义实用程序.我记得我是从google搜索获得的;).

http://www.javapractices.com/topic/TopicAction.do?Id=96

  • 我监督了一个更好的解决方案.我们的apache朋友有StringEscapeUtils(org.apache.commons.lang.StringEscapeUtils).请检查它是否有效. (3认同)