Header and Body an Authentication Example
suggest changeThe @Header and @Body annotations can be placed into the method signatures and Retrofit will automatically create them based on your models.
public interface MyService {
@POST("authentication/user")
Call<AuthenticationResponse> authenticateUser(@Body AuthenticationRequest request, @Header("Authorization") String basicToken);
}
AuthenticationRequest is the model, a POJO, containing the information the server requires. For this example, the server wants the client key and secret.
public class AuthenticationRequest {
String clientKey;
String clientSecret;
}
Notice that in @Header("Authorization") we are specifying we are populating the Authorization header. The other headers will be populated automatically since Retrofit can infer what they are based on the type of objects we are sending and expecting in return.
We create our Retrofit service somewhere. We make sure to use HTTPS.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.com/")
.client(client)
.build();
MyService myService = retrofit.create(MyService.class);
client is the HTTP client you built elsewhere. @Body needs a converter, such as GsonConverterFactory, on this Retrofit.Builder. The base URL has to end with /.
Then we can use our service.
AuthenticationRequest request = new AuthenticationRequest();
request.clientKey = getClientKey();
request.clientSecret = getClientSecret();
String basicToken = "Basic " + token;
Call<AuthenticationResponse> call = myService.authenticateUser(request, basicToken);
authenticateUser returns a Call. Nothing is sent until that call is enqueued or executed. token comes from the surrounding code.