Reputation: 9913
I am consuming a web service which presents its responses as an HTTP-style list of key-value pairs. I want to parse them into a HashMap. I do not want to write the parser. I want to revise my current hackish solution, a string.split("&")
followed by a series of string.split("=")
calls with logic interspersed.
Does anybody out there in SO-land know of references to a library that will do this? I browsed around in Apache and javax but didn't see much. I'm doing this in Android.
A simple example of a response is:
result=success&id=8a8d3c30-e184-11e1-9b23-0800200c9a66&name=wahooooooo
The ideal function:
public HashMap<String, String> parse(InputStream in);
Upvotes: 0
Views: 3311
Reputation: 2275
Already answered but here is an alternative to URLEncodedUtils
public static HashMap<String, String> getQueryString(String url) {
Uri uri= Uri.parse(url);
HashMap<String, String> map = new HashMap<>();
for (String paramName : uri.getQueryParameterNames()) {
if (paramName != null) {
String paramValue = uri.getQueryParameter(paramName);
if (paramValue != null) {
map.put(paramName, paramValue);
}
}
}
return map;
}
Upvotes: 0
Reputation: 701
if you have apache libraries, you can use URLEncodedUtils class like this :
HashMap<String, String> parameters = new HashMap<String, String>();
String query = "result=success&id=8a8d3c30-e184-11e1-9b23-0800200c9a66&name=wahooooooo";
List<NameValuePair> params = URLEncodedUtils.parse(query, Charset.defaultCharset());
for (NameValuePair nameValuePair : params) {
parameters.put(nameValuePair.getName(), nameValuePair.getValue());
}
Upvotes: 5
Reputation: 2794
You can use UrlEncodedUtils
just invoke URLEncodedUtils.parse(yourString,Charset.forName("UTF-8")).
and you will get a List<NameValuePair>
containing name and value associated elements.
see this : HttpComponents
here is a simple program
Upvotes: 2