简体   繁体   English

从Web API到Android获取OAuth令牌

[英]Get OAuth Token from Web API to android

I'm trying to get ِِOAuth token in android from my web api. 我正在尝试从Web API获取android中的ِِ OAuth令牌。 I have tested the api in Postman and it's working perfect. 我已经在Postman中测试了api,并且运行良好。

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. 现在,我需要使用改造2从我的android应用程序中调用此Api以获取令牌,因为我尝试使用以下界面,但无法正常工作。

@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. 就我而言,我使用以下方式在Android应用程序中调用Web Api。

Note : I am using OkHttp library. 注意:我正在使用OkHttp库。

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. 现在将OkHttp库jar添加到您的项目中。

for more detail visit this : 有关更多详细信息,请访问:

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

Now to get OAuth Token call this way 现在以这种方式获取OAuth令牌调用

            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 TokenResponse类

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 我正在使用改造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);
                }
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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