问题
I am working on android mobile application for website I have a url username and password.I need to login through app.How it should be done? Do I need to use any library for authentication.Any help would be appreciated.Thanks in advance!
回答1:
Network requests with Android should be done with a library, such as Retrofit or Volley. If you are new to Android and/or looking for a quick solution to your login, I suggest trying Volley as it takes less experience to set up. Here is a good resource to learn about Volley.
Another good option, and the most widely adopted solution as of current is Retrofit. If you are doing anything more than a few simple network calls in your app, I strongly suggest learning about Retrofit. It takes a bit more Android knowledge in my opinion, but it is a more elegant solution and worth the learning.
You will have to learn to make a POST request to your API using either of these libraries, passing in the username and password as parameters or in the request body. The API will likely return a token for authentication in the response body. Good luck!
回答2:
First you have to implement some rest api libraries.
implementation('com.squareup.retrofit2:retrofit:2.1.0') {
exclude module: 'okhttp'
}
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.0'
implementation 'com.squareup.okhttp3:okhttp:4.2.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
Then after create class ApiClient.. in this class write below code in it
public class ApiClient {
private static Retrofit retrofit = null;
public 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("https://jsonplaceholder.typicode.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}}
Now create Interface ApiInterface and write below code in it..
public interface ApiInterface {
@FormUrlEncoded
@POST("login/")
Call<Your Pojo Class> loginuser(@Field("method") String method, @Field("login_name")
String loginname,@Field("password") String password);}
In your MainActivity Write belowe code..
APIInterface apiInterface;
apiInterface = APIClient.getClient().create(APIInterface.class);
Call<EarnAmount> call = apiInterface.loginuser("loginuser", loginid,password);
call.enqueue(new Callback<Your Pojo>() {
@Override
public void onResponse(Call<Your Pojo> call, Response<Your Pojo> response) {
//you will get some response
//you can handle response from here
}
@Override
public void onFailure(Call<Your Pojo> call, Throwable t) {
//check internet connection or something went wrong
}
}); }
来源:https://stackoverflow.com/questions/59464257/login-using-url-with-username-and-password-in-android-mobile-app