1

I try to receive token via POST json {"email":"test@example.com","password":"test"}. In postman it works: Postman request. I try do the same in Android Studio. I create class Token:

   public class Token {
    @SerializedName("token")
    @Expose
    public String token;
   }

And class APIclient

    class APIClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        retrofit = new Retrofit.Builder()
                .baseUrl("http://mybaseurl.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }

}

and interface APIInterface:

    interface APIInterface {
    @POST("/authenticate")
    Call<Token> getLoginResponse(@Body AuthenticationRequest request);
}

and class AuthenticationRequest:

    public class AuthenticationRequest {
    String email;
    String password;
}

In onCreate in MainActivity:

  apiInterface = APIClient.getClient().create(APIInterface.class);
  authenticationRequest.email="test@example.com";
  authenticationRequest.password="test";
  getTokenResponse();

And here is my getTokenResponse method:

    private void getTokenResponse() {
    Call<Token> call2 = apiInterface.getLoginResponse(authenticationRequest);
    call2.enqueue(new Callback<Token>() {
        @Override
        public void onResponse(Call<Token> call, Response<Token> response) {
            Token token = response.body();
        }
        @Override
        public void onFailure(Call<Token> call, Throwable t) {
            call.cancel();
        }
    });
}

And this is what I see in Logcat:

    03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> POST http://mybaseurl.com/authenticate http/1.1
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Type: application/json; charset=UTF-8
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Length: 46
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: {"email":"test@example.com","password":"test"}
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> END POST (46-byte body)

Could you tell me what I'm doing wrong? I need to give token every time when I'd like to get information from server via GET method. How can I receive and save token in Android code?

mkal91
  • 11
  • 1
  • 3

3 Answers3

4

Try this

 interface APIInterface {
  @POST("/authenticate")
  Call<Token> getLoginResponse(@Header("Authorization") String token, @Body AuthenticationRequest request);
 }

token is the Bearer token

Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
3

you should add application/json to header

interface APIInterface {
@Headers({"Content-Type: application/json", "Accept: application/json"})
@POST("/authenticate")
Call<Token> getLoginResponse(@Body AuthenticationRequest request);
}
Levi Moreira
  • 11,917
  • 4
  • 32
  • 46
Navneet Krishna
  • 5,009
  • 5
  • 25
  • 44
0

To get access token from you need to get header from response and read values from headers.

Callback<User> user = new Callback<User>() {
    @Override
    public void success(User user, Response response) {
        List<Header> headerList = response.getHeaders();
        //iterating list of header and printing key/value. 
        for(Header header : headerList) {
            Log.d(TAG, header.getName() + " " + header.getValue());
        }
    }
}

After you get the value you need from header i.e. AccessToken, you can store that value in Storage. e.g. SharedPreference

So next time when you need that value you can directly get that from Storage. e.g. SharedPreference

Now when you pass request for any webservice either that is GET or POST or any other method. You have to pass that into header requests.

@GET("/tasks")
Call<List<Task>> getTasks(@Header("Content-Range") String contentRange);

Or If you need to pass it every time, you can directly pass that from your Retrofit class.

Request request = original.newBuilder()
        .header("User-Agent", "Your-App-Name")
        .header("Accept", "application/vnd.yourapi.v1.full+json")
        .method(original.method(), original.body())
        .build();
Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40