Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java URLDecoder throws exception when used with a string containing a %

Tags:

java

url

decoding

I have a problem with the URLDecoder of Java. I am escaping a String in JavaScript, and send it to a java servlet. Then I decode the escaped String with the following line:

URLDecoder.decode(request.getParameter("text"), "UTF-8");

This works fine for every special characters I have tried, the only one making problems is the '%'. Everytime I use this character in the string, I get the following exception:

java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern
    java.net.URLDecoder.decode(URLDecoder.java:187)
    at.fhv.students.rotter.ajax.count.CountServlet.doGet(CountServlet.java:31)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Is this a known bug? Or is it really my mistake?

like image 884
Daniel Rotter Avatar asked May 14 '12 19:05

Daniel Rotter


People also ask

What is URLDecoder in java?

public class URLDecoder extends Object. Utility class for HTML form decoding. This class contains static methods for decoding a String from the application/x-www-form-urlencoded MIME format. The conversion process is the reverse of that used by the URLEncoder class.

How do you decodeURIComponent in Java?

to simulate decodeURIComponent . Java's URLDecoder decodes the plus sign to a space, which is not what you want, therefore you need the replace statements. The point is that you don't want encoded characters in a decoded string.

What is URL encoder in java?

Java URLEncoder is a utility class used to encode the URLs (Uniform Resource Locator). Reliability and security are ensured using Encoding of URL.


2 Answers

It is not a bug. You send a wrong encoded String. The %-sign has to be encoded as %25

If you call request.getParameter(), I think you get a decoded String.

like image 96
Christian Kuetbach Avatar answered Sep 22 '22 14:09

Christian Kuetbach


We had a similar issue in our angular application where we were encoding % sign once in client side code. When we received the value in servlet it was already decoded due to request.getParameter(). Since we already had URL decoder in our sever side code, decoding the % sign twice was causing a "URLDecoder: Incomplete trailing escape (%) pattern" exception. We figured out that we we should not encode and decode % as a value at all to get face this issue.

like image 42
ravindra nath Avatar answered Sep 18 '22 14:09

ravindra nath