I have face the same problem, while transfering the data over network.
Providing the sample code, which throws the Exception URLDecoder: Illegal hex characters in escape (%)
Sample Ajax Code which passes the string 'Yash %'
:
var encodedData = encodeURIComponent('Yash %');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "https://yash.ssl.com:8443/ServletApp/test", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+encodedData);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log("data uploaded successfully :: ");
}
};
Sevlet code which accepts the POST request.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println(" ===== ------ ===== /test | " + request.getParameter("data"));
String networkData = URLDecoder.decode( request.getParameter("data"), "UTF-8");
System.out.println("Ajax call data : "+ networkData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
As @Marcelo Rebouças
suggested before decoding a string, I am encoding it.
Java URLDecoder
class « The character "%" is allowed but is interpreted as the start of a special escaped sequence.
Javascript URL functions encodeURI() and encodeURIComponent()
// URLDecoder: Illegal hex characters in escape (%) pattern
String stringEncoded = URLEncoder.encode( request.getParameter("data"), "UTF-8");
String networkData = URLDecoder.decode( stringEncoded, "UTF-8");