anon
anon

Reputation:

Spring - changing Content-type HTTP header

I am communicating with a JSON API using Robospice. This is how I set the headers for a POST request:

mHttpHeaders = new HttpHeaders();
mHttpHeaders.add("Content-Type", "application/json");
Log.d(Global.TAG, mHttpHeaders.toString());

The problem is that I get a header which looks like that: {Content-Type=[application/json]} where I need to send Content-Type:application/json (which seems to be the only header that my server accepts). I can't find any way to change it (tried with both add() and setContentType() methods), how do I do that?

Upvotes: 2

Views: 21251

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

The output

{Content-Type=[application/json]}

you see in the Log statement is just the String returned by the toString() method, it's not the actual header sent. For example

public static void main(String[] args) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    System.out.println(headers);
}

prints

{Content-Type=[application/json]}

If you are using the HttpClient and HttpRequestBase (HttpGet, HttpPost, etc.) correctly, the header will be sent just fine.

Upvotes: 1

Shamim Ahmmed
Shamim Ahmmed

Reputation: 8383

You should try followings and it works for me. I'm using Spring rest template inside Robospice.

MediaType mediaType = new MediaType("application", "json");
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(mediaType);

HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);

Upvotes: 2

Related Questions