I have a java servlet application where I am using URLDecoder to decode the value of password
Here is the part of my code:
Map<String, String[]> paramMap = request.getParameterMap();
Set<String> keySet = paramMap.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext())
{
String key = iterator.next();
if (!key.equals("_")){
try {
String value = URLDecoder.decode(request.getParameter(key),"UTF-8");
System.out.println("Getting parameter("+ key +" = '" + value +"')");
}
}
The value doesn't get decoded if it contains '%'
I tried to use getQueryString() which return strings containing percentage, but it doesn't have method to extract particular parameter
String requestParamValue = URLDecoder.decode(request.getQueryString(),"UTF-8");
This returns:
Request raw param decoded is feature=check&userid=xyz#gmail.com&password=Asp%8]a/Asp%8]a/
Is there any way I can get the url decoded using request.getParameter(key) for the string containing '%'
Thanks
Percent symbol is a reserved character in URL encoding so it must be encoded itself. The servlet should fail with BAD REQUEST.
The string provided for password parameter should be URL encoded. Doing that in java:
String result = java.net.URLEncoder.encode("Asp%8]a/Asp%8]a/",java.nio.charset. StandardCharsets.UTF_8.name());
result ==> "Asp%258%5Da%2FAsp%258%5Da%2F"
Related
Url: https://myproject.dev.com/methodology/Culture?contentName=abc & def&path=Test&type=folder
Need to fetch only query params from above URL but problem is '&' in contentName=abc & def so while fetching the contentName getting the value in two parts like abc, def.
Please suggest the approach to get contentName is abc & def instead of abc,def.
If the & character is part of the name or value in the query string then it has to be percent encoded. In the given example: contentName=abc%26def&path=Test&type=folder.
If we pass any type of special character we have to encode those values. Java provides a URLEncoder class for encoding any query string or form parameter into URL encoded format. When encoding URI, one of the common pitfalls is encoding the complete URI. Typically, we need to encode only the query portion of the URI.
public static void main(String[] args) {
Map<String, String> requestParameters = new LinkedHashMap<>();
requestParameters.put("contentName", "abc & def");
requestParameters.put("path", "Test");
requestParameters.put("type", "folder");
String encodedURL = requestParameters.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParameters.get(key)))
.collect(Collectors.joining("&", "https://myproject.dev.com/methodology/Culture?", ""));
System.out.println(encodedURL);
}
private static String encodeValue(String value) {
String url = "";
try {
url = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (Exception ex) {
System.out.println(ex);
}
return url;
}
Output:
https://myproject.dev.com/methodology/Culture?contentName=abc+%26+def&path=Test&type=folder
I'm currently trying to catch special chars from an URL to change them to their hex value (for example : "This shop" should transform into "This%20shop").
I was wondering if there was some clean was of looking into the string to find each special chars and replace them to their ascii values.
I try to do it because I have to pass PHP arguments into the url using GET.
Here would be an example of an url :
www.mysite.com/page?adress=I am Living here!
My code actually reaplace '%' and ' ' from URLs, but I'd like to change any special chars I've defined.
This is what I've done so far :
private final String specialChars = "!#\\[]`#$%&'()*+-<>=?";
public URL getURL(){
String tempUrl = baseURL;
Set<String> keys = this.arguments.keySet();
for (Map.Entry<String, String> entry : arguments.entrySet()) {
String value = entry.getValue();
if(entry.getValue().contains(specialChars)){
Log.e("INFO", "THIS URL CONTAINS SPECIAL CHARS");
}
//Replacing % char
if(entry.getValue().contains("%")){
Log.i("URL BUILD INFO", "URL ARGS CONTAINS '%'");
value = entry.getValue().replace("%", "%25");
}
//Replacing spaces
if(entry.getValue().contains(" ")){
Log.i("URL BUILD INFO", "URL ARGS CONTAINS SPACE");
value = entry.getValue().replace(" ", "%20");
}
baseURL += entry.getKey() + "=" + value + "&";
}
try{
this.url = new URL(baseURL);
} catch(MalformedURLException e){
Log.e("URL MALFORMED", "YOUR IS MALFORMED");
e.printStackTrace();
}
Log.d("URL IS VALID", url.toString());
return url;
}
From what I understood from String documentation, matches method should only return true if my URL matches exactly my specialChars charSequence, which isn't what I want. But I can't find any other method to do what I'm trying to achieve on the String documentation.
If you're just trying to handle url encoding there are existing solutions for that - see URLEncoder and URLDecoder (good previous answer here)
I have URL like http://example.com/foo/?locale=en_US&xyz, when i do a getQueryString() on the URL i get back an empty String
I am doing "request.getQueryString()" on the URL
getQuery() works for me:
String str = "http://example.com/foo/?locale=en_US&xyz";
URL url = new URL(str);
System.out.println(url.getQuery());
Output: locale=en_US&xyz
Doc says
Returns: a String containing the query string or null if the URL
contains no query string. The value is not decoded by the container.
The value is not decoded by the container.
String queryString = URLDecoder.decode(request.getQueryString(), "UTF-8");
This will make getQueryString() work.
Recommend to get params using getParameter()
I am fetching data from server in my project. In some condition there is a need to send + operator in url with parameter. How can i send "+" in url with parameter.
here is my url
http://www.needsthesupermarket.com/webservice/dp/addCart.php?cart_id=43530&cust_id=13936&pid=11303&qty=1&combination=2 ltr + 1 kg&guest_id=2509245
In blank space i replace with %20. but problem with + sign. How can i send it in url?
%26 -> &
%2B -> +
You can decode/encode here
You should encode your GET parameters:
Uri.encode(someParam)
For example if you have some Map paramsGet with GET parameters:
final StringBuilder url = new StringBuilder("http://example.com");
String delim = "?";
for (final Map.Entry<String, String> entry : paramsGet.entrySet()) {
url.append(delim).append(entry.getKey()).append("=").append(Uri.encode(entry.getValue()));
delim = "&";
}
To Encode use
String encodedInput = java.net.URLEncoder.encode(inputText, "UTF-8");
To Decode use
String decodedInput = java.net.URLDecoder.decode(encodedInput, "UTF-8");
I am implementing a chat system and I am running into a problem while parsing the message.
As part of the message string, I have sending a bunch of key params like this
key1:value1,key2:value2,key3:value3,message:"random text with character : /" etc.
I will later parse this string using split on command and colon. However one of the params is message which can contain both command and colon. so if the message has any of those characters, it will break my parse logic. So is there any way I can escape these characters in the message string? I tried adding two backslashes to escape it but that did not work.
parse code
String[] params = chat.split(",");
for(String param:params){
String[]pair = param.split(":");
if(pair.length != 2){
String key = pair[0];
String value = pair[1];
}else{
return null;
}
}
you question isn't clear i need more example and the best way to receive the messages in JSON format thats makes your job much more cleab but i provide two answers .
For just getting the message as raw( if you are sure that the key value will be "message" and capture everything in the second part):
for(String param:params){
if (param.contains("message")){
String[] pairs=param.split("message:");
String key = "message";
String value = pairs[1];
}
String[]pair = param.split(":");
if(pair.length != 2){
String key = pair[0];
String value = pair[1];
}else{
return null;
}
}
return:
"random text with character : /" etc.
For escaping the special character in string you have to use the following method :
for(String param:params){
if (param.contains("message")){
String[] pairs=param.split("message:");
String key = "message";
String value = StringEscapeUtils.escapeJava(pairs[1]);
}
String[]pair = param.split(":");
if(pair.length != 2){
String key = pair[0];
String value = pair[1];
}else{
return null;
}
return:
\"random text with character : /\" etc.
you have to import Apache Commons Lang ยป 3.0 here is the link for maven :
http://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.0