简体   繁体   中英

Get OAuth Token from Web API to android

I'm trying to get ِِOAuth token in android from my web api. I have tested the api in Postman and it's working perfect.

Screenshot for the successful call from Postman

now I need to call this Api from my android app using retrofit 2 to get the token, for that I tried to use the following interface but it's not working.

@FormUrlEncoded
@POST("/Token")
public Call<String> Token(@Field("grant_type") String grant_type, @Field("username") String username, @Field("password") String password);

How can I get this done?

In my case I using this below way to call Web Api in Android Application.

Note : I am using OkHttp library.

Create Token class

public class Token {
    public String access_token;
    public String token_type;
    public int expires_in;

    public Token(){

    }
}

Now add OkHttp library jar to your Project.

for more detail visit this :

http://square.github.io/okhttp/

Now to get OAuth Token call this way

            OkHttpClient client = new OkHttpClient();
            Request.Builder builder = new Request.Builder();
            builder.url(write your url here);
            builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
            builder.addHeader("Accept", "application/json");

            FormEncodingBuilder parameters = new FormEncodingBuilder();
            parameters.add("grant_type", "password");
            parameters.add("username", edituser);
            parameters.add("password", editpassword);
            builder.post(parameters.build());

            try {
                Response response = client.newCall(builder.build()).execute();
                if (response.isSuccessful()) {
                    String json = response.body().string();

                }
            catch(Exception e){
              // catch Exception here
          }

finally in response you will get your Token.

Late but it might help someone

Interface class

@FormUrlEncoded
    @POST("/Token")
    void getTokenAccess(@Field("grant_type") String grantType, @Field("username") String username, @Field("password") String password, Callback<TokenResponse> callback);

TokenResponse class

public class TokenResponse {
    private String access_token,token_type,expires_in,userName;

    public String getAccess_token() {
        return access_token;
    }

    public String getToken_type() {
        return token_type;
    }

    public String getExpires_in() {
        return expires_in;
    }

    public String getUserName() {
        return userName;
    }
}

I am using retrofit 1.9.0

RestAdapter adapter = new RestAdapter.Builder()
                    .setEndpoint(ENDPOINT_URL).setLogLevel(RestAdapter.LogLevel.FULL)
                    .build();
            NetApi api = adapter.create(NetApi.class);

            api.getTokenAccess("password", email, password, new Callback<TokenResponse>() {


                @Override
                public void success(TokenResponse tokenResponse, Response response) {
                    showProgress(false);
                    try{
                        MainActivity.tokenResponse = tokenResponse;
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    }catch (Exception e){
                        Toast.makeText(LoginActivity.this,"Unknown Error",Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    Toast.makeText(LoginActivity.this,""+error.getMessage(),Toast.LENGTH_LONG).show();
                    showProgress(false);
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM