QED QED - 1 year ago 60
Java Question

Parse HTTP-style key-value pairs into java.util.HashMap

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

followed by a series of
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:


The ideal function:

public HashMap<String, String> parse(InputStream in);

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download