locked
How to login from android client to WebApi RRS feed

  • Question

  • User729207731 posted

    i have build webapi login for mvc, webforms and android client, in ASP.NET MVC or webforms i login web api successfully. but in android i don't know to login my system

    here my api respose result.

    use postman 10.1.1.2/token

    {
        "access_token": "1X15v6bwJAOWLtzuh8Gw62GmIX3p8x01HvatqkT0lYHB5cMICEUrzdT4YVmC2nQrdPQ6yYiAk3Ivjjh7P1O_NDe9MspxBMGBVaOcA0SnePI1aC17_ahPvxW4dJTPeip7dd5U-tiOsXOpCQMi0lHPocBV7GNsNzHtkL-LH7uIsNENKuHidyBfRUyNMJ8dwgWaLbpJaEQrtbIcWUQZNU_iDPPCgQEiBpYyUf8IWdQRAXaWNdk7gmloYkOZDOroL0zmzNPsPAHrwKFqJgUDmu3Km-zCcVX2uIzQ2DkOlCgoy-p0d4zgzH3tG02aXPY8-E2mNPdWeFhgi37PFMnvx0CgsdJzsNsH16YaPTosYA9VCjaCl2xuKK7A31Zpc1rwpoJjOlePVVuHu-7cC8214p3Y3CHvk9-niJonuASNyJKrLLUnmkJNsEkRFqtcw0qqvVI22QFN7q4O5yB9azbs6SMs_RPr_3vOlaHDsPtBNvRU_Qc",
        "token_type": "bearer",
        "expires_in": 1209599,
        "userName": "hoitm",
        ".issued": "Fri, 16 Jun 2017 07:08:33 GMT",
        ".expires": "Fri, 30 Jun 2017 07:08:33 GMT"
    }

    and in android client 

    i have many class

    public class AuthenticationInterceptor implements Interceptor {
        private String authToken;
    
        public AuthenticationInterceptor(String token) {
            this.authToken = "Bearer " + token;
        }
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
    
            Request.Builder builder = original.newBuilder()
                    .header("Authorization", authToken);
    
            Request request = builder.build();
            return chain.proceed(request);
        }
    }

    and Tokenmodel

    public class TokenModel {
    
        @SerializedName("access_token")
        @Expose
        private String accessToken;
        @SerializedName("token_type")
        @Expose
        private String tokenType;
        @SerializedName("expires_in")
        @Expose
        private Integer expiresIn;
        @SerializedName("userName")
        @Expose
        private String userName;
        @SerializedName(".issued")
        @Expose
        private String issued;
        @SerializedName(".expires")
        @Expose
        private String expires;
    
        public String getAccessToken() {
            return accessToken;
        }
    
        public void setAccessToken(String accessToken) {
            this.accessToken = accessToken;
        }
    
        public String getTokenType() {
            return tokenType;
        }
    
        public void setTokenType(String tokenType) {
            this.tokenType = tokenType;
        }
    
        public Integer getExpiresIn() {
            return expiresIn;
        }
    
        public void setExpiresIn(Integer expiresIn) {
            this.expiresIn = expiresIn;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getIssued() {
            return issued;
        }
    
        public void setIssued(String issued) {
            this.issued = issued;
        }
    
        public String getExpires() {
            return expires;
        }
    
        public void setExpires(String expires) {
            this.expires = expires;
        }
    
    }
    

    and  

    public interface UserService {
        @POST("/Token")
        Call<TokenModel> me();
    }
    

    public class ServiceGenerator {
        public static final String API_BASE_URL = "http://10.1.1.2";
    
        private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
        private static Retrofit.Builder builder =            new Retrofit.Builder()
                        .baseUrl(API_BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create());
        private static Retrofit retrofit = builder.build();
        public static <S> S createService(Class<S> serviceClass) {
            return createService(serviceClass, null);
        }
    
        public static <S> S createService( Class<S> serviceClass, final String authToken) {
            if (!TextUtils.isEmpty(authToken)) {
                AuthenticationInterceptor interceptor =    new AuthenticationInterceptor(authToken);
    
                if (!httpClient.interceptors().contains(interceptor)) {
                    httpClient.addInterceptor(interceptor);
                    builder.client(httpClient.build());
                    retrofit = builder.build();
                }
            }
            return retrofit.create(serviceClass);
        }
    }
    

    main activity

    public class MainActivity extends Activity {
        Button b1,b2;
        EditText ed1,ed2;
    
        TextView tx1;
        int counter = 3;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            b1 = (Button)findViewById(R.id.button);
            ed1 = (EditText)findViewById(R.id.editText);
            ed2 = (EditText)findViewById(R.id.editText2);
    
            b2 = (Button)findViewById(R.id.button2);
            tx1 = (TextView)findViewById(R.id.textView3);
            tx1.setVisibility(View.GONE);
    
            b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if( login success) { 
                        //Toast.makeText(getApplicationContext(),   "Redirecting...",Toast.LENGTH_SHORT).show();
    
    how to call retrofit login
                    }else{
                        Toast.makeText(getApplicationContext(), "Wrong  Credentials",Toast.LENGTH_SHORT).show();
                        tx1.setVisibility(View.VISIBLE);
                        tx1.setBackgroundColor(Color.RED);
                        counter--;
                        tx1.setText(Integer.toString(counter));
    
                        if (counter == 0) {
                            b1.setEnabled(false);
                        }
                    }
                }
            });
    
            b2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    in mainactivity how to call retrofit login and set authentication bearer.

    i'm new to android thanks so much.

    Friday, June 16, 2017 7:13 AM

All replies

  • User729207731 posted

    and In Weather api   return result.

    [
        {
            "Id": 1,
            "CountryName": "Dhaka, Bangladesh",
            "Temperature": "88 F"
        },
        {
            "Id": 2,
            "CountryName": "Washington, DC",
            "Temperature": "65 F"
        },
        {
            "Id": 3,
            "CountryName": "Mumbai, Maharashtra, India",
            "Temperature": "90 F"
        },
        {
            "Id": 4,
            "CountryName": "London, UK",
            "Temperature": "56 F"
        }
    ]

    in java class pojo 

    public class Weather {
    
        @SerializedName("Id")
        @Expose
        private Integer id;
        @SerializedName("CountryName")
        @Expose
        private String countryName;
        @SerializedName("Temperature")
        @Expose
        private String temperature;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getCountryName() {
            return countryName;
        }
    
        public void setCountryName(String countryName) {
            this.countryName = countryName;
        }
    
        public String getTemperature() {
            return temperature;
        }
    
        public void setTemperature(String temperature) {
            this.temperature = temperature;
        }
    
    }

    how to call weather api with token bearer. thanks

    Friday, June 16, 2017 7:16 AM
  • User1967761114 posted

    Hi hitm

    According to your description, I’m unsure which weather API you are using.

    The general ways to using bearer token you could refer to the following format:

    (1) Http Header

    GET /resource HTTP/1.1
    Host: server.example.com
    Authorization: Bearer XXXXXXXXX

    (2) POST (Form)

    POST /resource HTTP/1.1
    Host: server.example.com
    Content-Type: application/x-www-form-urlencoded
    
    access_token=XXXXXXXXX

    (3) GET(Query String)

    GET /resource?access_token=XXXXXXXXX
    Host: server.example.com

     

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Monday, June 19, 2017 3:34 AM