Home > front end >  Can API keys be added to the header using Retrofit2 android
Can API keys be added to the header using Retrofit2 android

Time:12-06

Cannot get the API request to work with the API key. Have already tested it with a different API that doesn't use an API Key, which has worked. Makes me think that I'm not adding the API Key properly.

Tested it on postman using the authentication tab which works well.

How can I send the key Access-Key and value 9xxxxxxxxxxxxx3 using retrofit2?

code

CodePudding user response:

When you call R.string.api_key, you don't get the String value, you only get its id, which is represented as a number. To get the value you need to have context and call context.getString(R.string.api_key). In our case, it is better to take it out from string.xml and place it in some class. For example

object Constants {
    const val BASE_URL = "http://test.com/"
}

and then inside the retrofit

 return Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)

but if you want to get the value from string.xml you need to change getInstance() method from example add Context.

CodePudding user response:

You can send Headers like as:

public interface APIService {

//Login
@FormUrlEncoded
@POST("loginAction")
Call<LoginModel> loginMI(
        @Field("username") String username,
        @Field("pwd") String pwd,
        @Header("api_key") String api_key,
        @Header("secret_key") String secret_key
);

}

call the above API and pass the required Field and Headers.

  • Related