简体   繁体   中英

Why does getHeaderField() return a String where as getHeaderFields() return Map<String,List<String>> in HttpUrlConnection

I am using HttpUrlConnection in my android code and I am trying to access header fields post getResponseCode() call. For a single header method is -

public String getHeaderField(String name)

where as to get all headers it is -

public Map<String,List<String>> getHeaderFields()

So whats the deal here? Are we allowed to set headers multiple times?

Documentation of getHeaderField() method says -

If called on a connection that sets the same header multiple times with possibly different values, only the last value is returned.

So whats with getHeaderFields() method? I would appreciate if someone could give an example to help understand the difference.

Comparing with HttpResponse which has method -

Header[] getHeaders(String var1);

I would have expected method -

public List<String> getHeaderField(String name)

but that does not seem to be the case. So how do I handle this?

Headers (not sure if all of them) can have multiple values, and I don't know why the API was designed this way ( getHeaderField() returns the values separated by ; while getHeaderFields() returns a list of values, which is an inconsistent design choice in my opinion).

Well, to get a list of values for some header: getHeaderFields() method returns a map, so if you already know the header name, you don't need to iterate, just do getHeaderFields().get("headername") to get the list of values of that header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM