Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Header Parameter in Retrofit

I'm trying to call an API which requires me to pass in an API key.

My Service call using HttpURLConnection is working perfectly.

url = new URL("https://developers.zomato.com/api/v2.1/search?entity_id=3&entity_type=city&q=" + params[0]); urlConnection = (HttpURLConnection) url.openConnection();  urlConnection.setRequestProperty("user-key","9900a9720d31dfd5fdb4352700c");  if (urlConnection.getResponseCode() != 200) {     Toast.makeText(con, "url connection response not 200 | " + urlConnection.getResponseCode(), Toast.LENGTH_SHORT).show();     Log.d("jamian", "url connection response not 200 | " + urlConnection.getResponseCode());     throw new RuntimeException("Failed : HTTP error code : " + urlConnection.getResponseCode()); } 

However, I'm not sure how this works with Retrofit as my call in going into Failure at all times. Here's the code I'm using for the same service call

@GET("search") Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query,@Header("Accept") String accept, @Header("user-key") String userkey); 

and I'm using this to call it

Call<String> call = endpoint.getRestaurantsBySearch("3","city","mumbai","application/json","9900a9720d31dfd5fdb4352700c"); 

All these calls are going into the OnFailure Method in RetroFit. If I send it without the HeaderParameters it goes into Success with a 403 because I obviously need to pass the api key somewhere but I cant figure out how.

@GET("search") Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query); 

The error I'm getting in OnFailure is

java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $ 
like image 461
jamian Avatar asked Mar 20 '17 08:03

jamian


People also ask

How do I add a header in OkHttp?

Adds a header with name and value. Prefer this method for multiply-valued headers like "Cookie". Note that for some headers including Content-Length and Content-Encoding, OkHttp may replace value with a header derived from the request body.

How do you send parameters in retrofit?

You can pass parameter by @QueryMap Retrofit uses annotations to translate defined keys and values into appropriate format. Using the @Query("key") String value annotation will add a query parameter with name key and the respective string value to the request url .


2 Answers

Try this type header for Retrofit 1.9 and 2.0. For the 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 your method, i.e.,

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

Or

Want to pass every time, then create an HttpClient object with the 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 a Retrofit object

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

If you are using Kotlin, remove the { }. Else it will not work.

like image 193
Avinash Verma Avatar answered Sep 21 '22 13:09

Avinash Verma


You can use the below

 @Headers("user-key: 9900a9720d31dfd5fdb4352700c")  @GET("api/v2.1/search")  Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query); 

and

 Call<String> call = endpoint.getRestaurantsBySearch("3","city","cafes"); 

The above is based in the zomato api which is documented at

https://developers.zomato.com/documentation#!/restaurant/search

Thing to note is the end point change api/v2.1/search and the Header @Headers("user-key: 9900a9720d31dfd5fdb4352700c").

Also check your base url .baseUrl("https://developers.zomato.com/")

Also i tried the above with a api key i generated and it works and my query was cafes as suggested the zomato documentation.

Note : I hope you have the below

 .addConverterFactory(ScalarsConverterFactory.create()) // for string conversion  .build(); 

and the below in build.gradle file

compile group: 'com.squareup.retrofit2', name: 'converter-scalars', version: '2.2.0' 

Edit:

You can also pass header with dynamic value as below

@GET("api/v2.1/search") Call<String> getRestaurantsBySearch(@Query("entity_id") String entity_id, @Query("entity_type") String entity_type, @Query("q") String query,@Header("user-key") String userkey); 

And

Call<String> call = endpoint.getRestaurantsBySearch("3","city","cafes","9900a9720d31dfd5fdb4352700c"); 
like image 35
Raghunandan Avatar answered Sep 19 '22 13:09

Raghunandan