42

My Api is accepting Content-Type application/json as headers. I set Header perfectly as mentioned in Retrofit Docs.

@Headers("Content-Type: application/json")
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);

But in Request Log it is Returning Content-Type txt/html.So how i should fix this issue? This api works fine in POSTMAN enter image description here

enter image description here

10
  • I don't think it is an issue with Retrofit. Normally the websites return results in txt/html. You should query the api with something like ?format=json. You can simply check that by opening the api url directly in the browser. Mar 2, 2016 at 12:44
  • Please post the html request and the postman request. Mar 2, 2016 at 12:50
  • @Christopher updated the question with postman request Mar 2, 2016 at 12:56
  • Its returning http error code 405: Method not allowed. You should look into that.
    – Rohit5k2
    Mar 2, 2016 at 13:11
  • 1
    @Zubair can you show me your working code, actually, I am facing same issue Jul 27, 2017 at 14:23

8 Answers 8

43

Try this type header for Retrofit 1.9 and 2.0. For Json Content Type.

@Headers({"Accept: application/json"})
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);

You can add many more headers i.e

@Headers({
        "Accept: application/json",
        "User-Agent: Your-App-Name",
        "Cache-Control: max-age=640000"
    })

Dynamically Add to headers:

@POST("user/classes")
Call<ResponseModel> addToPlaylist(@Header("Content-Type") String content_type, @Body RequestModel req);

Call you method i.e

mAPI.addToPlayList("application/json", playListParam);

Or

Want to pass everytime then Create HttpClient object with http Interceptor:

OkHttpClient httpClient = new OkHttpClient();
        httpClient.networkInterceptors().add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });

Then add to retrofit object

Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();

UPDATE if you are using Kotlin remove the { } else it will not work

22

you can try one in below my solutions :

@POST("user/classes")
Call<playlist> addToPlaylist(@Header("Content-Type") String content_type, @Body PlaylistParm parm);

then call

mAPI.addToPlayList("application/json", playListParam);

Or

Create HttpClient object

OkHttpClient httpClient = new OkHttpClient();
        httpClient.networkInterceptors().add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });

Then add to retrofit object

Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
6
  • Thanks for your reply. I tried to request using both ways, But didn't works for me :( Mar 3, 2016 at 9:25
  • could you provide me the data for requesting if you don't mind
    – ThaiPD
    Mar 3, 2016 at 9:30
  • groopiesdev.com/api/v1/user/classes Authorization Basic ZXlKbGVIQWlPakUwTlRjd01EVTVNRE1zSW1Gc1p5STZJa2hUTWpVMklpd2lhV0YwSWpveE5EVTJPVEU1TlRBemZRLmV5SnBaQ0k2TnpKOS5wbExhZmNxVVBoVGZpV2prLXFDREQ2eXQwQ0tSdlc0R0c1eHJ2enRHNXBnOjE= Content-Type application/json {"userid":72, "classid":38} Mar 3, 2016 at 9:38
  • when I try to use your data by postman I got error : Error: 500 Internal Server Error
    – ThaiPD
    Mar 4, 2016 at 9:39
  • Actullay issue is my request is POST.But in Request Log it is showing GET Request..log..i don't know how it is converted in GET automatically Mar 7, 2016 at 6:51
8

Here's a solution that works as of retrofit2(v2.5) and okhttp3. Works especially well if you will add these headers to a number of requests

OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                requestBuilder.header("Accept", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });

 OkHttpClient httpClient = httpClientBuilder.build();
 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();
4

Try:

@POST("user/classes")
Call<playlist> addToPlaylist(
@Header("Content-Type") String contentType,
@Body PlaylistParm parm);
3

Retrofit 2.0 drove me nuts. I finally gave up and tried: Android Async Http

And it worked first time. I know what you are thinking that I am looking for stckovflw points or I am somehow flaming Retrofit. I am not. My use case was to call my bitbucket account with a simple inline authentication: https://[username]:[password]@api.bitbucket.org/2.0/repositories/[username]

With Retrofit I was getting another response. An Http 200 but not the payload I would expect, as you would get from Postman. I tried everything I could find to get it to work. Wasted I think 2 days on it or more. I guess you might be thinking, well, you did not form your baseUrl correctly...or the URI for the resource. Look at the above, how less complicated can it be...I tried shortening the URI to the min. and setting the baser URL to the longest part of the above; reminder: I got an Http 200 back. But not the correct response payload!

A colleague of mine suggested using the asynch lib. and given all the recommendations for Retrofit and the time I had spent, I was skeptical. It worked first time!!

1
  • 1
    Beware. Loopj's Async Http is getting old and unmaintained. I had a lot of bugs with SSL and time-outs that I couldn't replicate in any other http client. The last few code changes were made in November 2017 and April 2016 and issues are piling up. Nov 6, 2018 at 6:24
3

We can specify header for particular request too.

    @Headers("Content-Type: application/json")
    @Get
    fun getData(@Url url:String):List<Obj>
        
0

maybe you need '/' and is best not to change the Content-Type by youself. just like this:

@POST("user/classes/")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
0

Using @Headers("Content-Type: application/json-patch+json") @PATCH("user/edit")

fixed the problem for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.