Chris McKee
Chris McKee

Reputation: 4387

How do I make Java return a HTTP header in JSON as a Key Value Array

I have the following as part of a method that is basically grabbing a webpage, I want to map the resulting header and body to JSON, the body is spat out as a string but ideally I want the header values split into key value so in the JavaScript I can access them directly.

Map<String, String> assoc = new HashMap<String, String>();

Map<String, List<String>> headerMap = new LinkedHashMap<String, List<String>>();
headerMap = connection.getHeaderFields();

for (String key : headerMap.keySet()) {
    assoc.put(key, headerMap.get(key).toString());
}

JSONObject returnObj = new JSONObject();
returnObj.put("header", assoc);
returnObj.put("body", sb.toString());

return returnObj.toString(); //Set digit to add indent spacing.

This unfortunately returns the header as a string rather than an array...

{"header":"{cache-control=[max-age=0], content-type=[text\/html], connection=[Keep-Alive],

Ideally this would be more like (friendlier for javascript)...

{
    "headers": [
        {"test": "testval"},
        {"testb": "testbval"}
    ]
}

Upvotes: 1

Views: 4152

Answers (2)

jeffb
jeffb

Reputation: 360

JSONObject returnObj = new JSONObject();
for (String key : headerMap.keySet()) {
    returnObj.put(key, headerMap.get(key).toString());
}
return returnObj.toString();

I have not used this api before, but from the javadoc I am pretty sure the code above will give you what you want. Since you are only dealing with one set of data (the header object), this method will work. If you had many objects, you would have to do something different. Try flexjson, that is one I use often.

Also, the reason you are getting your current output is the JSONObject.put is calling the Map's toString() which produces a string of all key/value pairs represented as "key=value" separated by a comma and wrapped in curly brackets.

{"key1=value1", "key2=value2", etc..}

Upvotes: 3

tryurbest
tryurbest

Reputation: 1429

I think you are probably looking for

{"header":[
             {"cache-control=[max-age=0]"},
             {"content-type=[text\/html]"},
             {"content-type=[text\/html]"}
          ]}

Upvotes: 0

Related Questions