Reputation: 31086
In my Java app, I can get name , value pairs from url, but a url with "&" as part of a value is causing problem, it looks like this:
http://localhost:6600/Resume_App?Id=Edit&File_Name=AT&T.txt
I know I can replace the string "AT&T" with "ATT" to avoid it, but I don't want to avoid it, there might be other cases, that I can't predict where this char might occur, so I want to solve it, I'm trying to come up with an intelligent way to tell if "&" is part of a value or not. So for values with "&" char, what's a good way to get name value pairs from it ?
Upvotes: 1
Views: 798
Reputation: 31086
After some trial and error, I finally figured it out :
[1] Use this to encode the URL :
public static String encode(String s)
{
try { return URLEncoder.encode(s,"UTF-8"); }
catch (UnsupportedEncodingException e)
{
Resume_App.Save_To_Log("UTF-8 is not a recognized encoding\n"+Tool_Lib_Simple.Get_Stack_Trace(e));
throw new RuntimeException(e);
}
}
[2] Use "exchange.getRequestURI().getRawQuery()" to get the raw query, I was using exchange.getRequestURI().getQuery() eariler, and it decodes the query for me, and made things confusing, what I need is the raw query.
[3] Use the following to get the name value map :
public LinkedHashMap<String,String> queryToMap(String query)
{
LinkedHashMap<String,String> result=new LinkedHashMap();
for (String param : query.split("&"))
{
String pair[]=param.split("=");
if (pair.length>1) result.put(pair[0],pair[1]);
else result.put(pair[0],"");
}
return result;
}
[4] Use the following to get decoded name value pairs :
for (Map.Entry<String,String> entry : params.entrySet())
{
paramName=entry.getKey().replace("+"," ");
try { paramValue=URLDecoder.decode(entry.getValue(),"utf-8"); }
catch (Exception e) { e.printStackTrace(); }
}
Upvotes: 1
Reputation: 311308
I think you're going at it the wrong way. Instead of trying to figure out if a certain &
is part of a value or an argument delimiter, encode the values before sending them to your app (e.g., by using URLEncoder
), and decode it on the other side.
Upvotes: 1