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
Solution 1:
In my case I using this below way to call Web Api in Android Application.
Note : I am using OkHttp library.
Create Token class
publicclassToken {
public String access_token;
public String token_type;
publicint expires_in;
publicToken(){
}
}
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
OkHttpClientclient=newOkHttpClient();
Request.Builderbuilder=newRequest.Builder();
builder.url(write your url here);
builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
builder.addHeader("Accept", "application/json");
FormEncodingBuilderparameters=newFormEncodingBuilder();
parameters.add("grant_type", "password");
parameters.add("username", edituser);
parameters.add("password", editpassword);
builder.post(parameters.build());
try {
Responseresponse= client.newCall(builder.build()).execute();
if (response.isSuccessful()) {
Stringjson= response.body().string();
}
catch(Exception e){
// catch Exception here
}
finally in response you will get your Token.
Solution 2:
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
publicclassTokenResponse {
privateString access_token,token_type,expires_in,userName;
publicStringgetAccess_token() {
return access_token;
}
publicStringgetToken_type() {
return token_type;
}
publicStringgetExpires_in() {
return expires_in;
}
publicStringgetUserName() {
return userName;
}
}
I am using retrofit 1.9.0
RestAdapteradapter=newRestAdapter.Builder()
.setEndpoint(ENDPOINT_URL).setLogLevel(RestAdapter.LogLevel.FULL)
.build();
NetApiapi= adapter.create(NetApi.class);
api.getTokenAccess("password", email, password, newCallback<TokenResponse>() {
@Overridepublicvoidsuccess(TokenResponse tokenResponse, Response response) {
showProgress(false);
try{
MainActivity.tokenResponse = tokenResponse;
startActivity(newIntent(LoginActivity.this, MainActivity.class));
}catch (Exception e){
Toast.makeText(LoginActivity.this,"Unknown Error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Overridepublicvoidfailure(RetrofitError error) {
Toast.makeText(LoginActivity.this,""+error.getMessage(),Toast.LENGTH_LONG).show();
showProgress(false);
}
});
Post a Comment for "Get Oauth Token From Web Api To Android"