Jwt token refresh? - android

I have an API for refreshing a token, but I am not able to use refresh token in my app, after a user login a token gets expired after 60min so now I want to refresh the user token, how can I use refresh token in my app
my interface of refresh token:
#POST("/api/token/refresh")
Call<ResponseBody> getAccessToken();
My Session:
public class Session {
Context context;
private SharedPreferences prefs;
private Session session;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
this.context = cntx;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setJwtToken(String token) {
prefs.edit().putString("token", token).commit();
}
public String getJwtToken() {
String token = prefs.getString("token", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
}
return token;
}
public String getRefreshToken() {
String token = prefs.getString("RefreshToken", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.getAccessToken();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
JSONObject resultObject = new JSONObject();
JSONObject tokenObject = null;
try {
tokenObject = resultObject.getJSONObject("token");
} catch (JSONException e) {
e.printStackTrace();
}
String newToken = null;
try {
newToken = tokenObject.getString("accessToken");
} catch (JSONException e) {
e.printStackTrace();
}
newToken = "Bearer " + newToken;
session.setJwtToken(newToken);
Log.e("Token Result Object", session.getJwtToken());
Log.e("Token Response Object", session.getRefreshToken());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
return token;
}
public void setRefreshToken(String token) {
prefs.edit().putString("RefreshToken", token).commit();
}
My login:
public class LoginActivity extends AppCompatActivity {
private Button userLogin;
ApiInterface apiInterface;
private EditText loginEmail, loginPassword;
private User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginEmail = findViewById(R.id.loginEmail);
loginPassword = findViewById(R.id.loginPassword);
userLogin = findViewById(R.id.loginButton);
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
TextView register = (TextView) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
ImageView back = (ImageView) findViewById(R.id.back_arrow_login);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
public void userLogin() {
final User user = new User();
final Session session = new Session(this);
user.setEmail(loginEmail.getText().toString().trim());
user.setPassword(loginPassword.getText().toString().trim());
apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.logMeIn(session.getJwtToken(),user);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 200) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject dataObject = jsonObject.getJSONObject("data");
String token = dataObject.getString("access_token");
String refToken = dataObject.getString("refresh_token");
session.setJwtToken("Bearer " + token);
session.setRefreshToken("Bearer"+refToken);
String name=user.getName();
Toast.makeText(LoginActivity.this, "WELCOME", Toast.LENGTH_SHORT).show();
Log.e("USER", jsonObject.toString());
startActivity(new Intent(LoginActivity.this, MainActivity.class));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else
Log.e("TestActivity", response.raw().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
Please help me clear out the method or process ,so that i can refresh the user token after it gets expired

public class ServiceFactory {
private static final long CONNECTION_TIMEOUT = 60 * 1000; // one minute
private Activity activity;
public ServiceFactory(Activity activity) {
this.activity = activity;
}
public static <T> T createService(final Class<T> clazz) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
public <T> T createServiceWithToken(final Class<T> clazz) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(getHttpClientBuilder())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
private OkHttpClient getHttpClientBuilder() {
// Setup OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.authenticator(new TokenAuthenticator());
return builder.build();
}
private void logout() {
if (activity != null) {
Intent intent = new Intent(activity, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
activity.finish();
}
}
class TokenAuthenticator implements Authenticator {
#Nullable
#Override
public Request authenticate(#NonNull Route route, #NonNull Response response) throws IOException {
TokenManager tokenManager = new TokenManager();
//called renew api call
retrofit2.Response<ResponseModel> responseModel= ServiceFactory.createService(YOUR_API.class)
.renewToken(tokenManager.getBearer())
.execute();
if (responseModel.code() == 401) {
//remove token
logout();
return null;
} else {
//saved token to local
}
//returned new reuwst with updated header
return response.request().newBuilder()
.header(APIConstants.AUTHORIZATION, tokenManager.getBearer())
.build();
}
}
}

Related

passing the results back to an activity from retrofit async call

i have setup retrofit client and the api interface, i have some code as follows
public Result<LoggedInUser> login(String username, String password) {
try {
apiInterface = ApiClient.getClient().create(ApiInterface.class);
RequestData requestData = new RequestData(username, password);
Call<RequestResponse> call = apiInterface.login(requestData);
call.enqueue(new Callback<RequestResponse>() {
#Override
public void onResponse(Call<RequestResponse> call, Response<RequestResponse> response) {
RequestResponse resource = response.body();
System.out.println(resource.getData().getAccessToken());
}
#Override
public void onFailure(Call<RequestResponse> call, Throwable t) {
call.cancel();
}
});
LoggedInUser fakeUser = new LoggedInUser(
java.util.UUID.randomUUID().toString(),
"Jane Doe");
return new Result.Success<>(fakeUser);
} catch (Exception e) {
return new Result.Error(new IOException("Error logging in", e));
}
}
I am not familar with the pattern that should be used to notify the repository class when the rest call obtains it's response.
the above code is called from the following code in the repository class
public Result<LoggedInUser> login(String username, String password) {
// handle login
Result<LoggedInUser> result = dataSource.login(username, password);
if (result instanceof Result.Success) {
setLoggedInUser(((Result.Success<LoggedInUser>) result).getData());
}
return result;
}

Retrofit returns not working access token

I'm creating an authorization app, where user registers and gets client_id, client_secret, access_token and refresh_token. I have one API where i need to do call. In that call I use my access_token. All works great. But the access_token expires after hour, so with refresh_token I'm updating my access_token, but the new access_token not works. When I'm doing call with this new access_token, the response body message is "expired access_token provided". In postman all works good. When I'm getting new access_token, in server visible only the access_token that i got from registration. So in server the access_token not updating. But when I'm doing this in postman, the access_token in server changes. So what's the problem, that in postman he updates the access_token, and in server the access_token changes, but when I'm updating in phone, the access_token in server not changes. I done debugging and i see that I'm getting new access_token. So where's the problem?
public interface SupportopApi {
//Post request for user register
#POST("/api/registration")
Call<ResponseBody> registrationRequest(#Body SupportopObjRegistration supportopObjRegistration);
//Post request for user activation
#POST("/api/getClientCD")
Call<ResponseBody> clientActivationRequest(#Body SupportopObjClient activate);
//Get request for getting token
#GET("/api/getToken")
Call<ResponseBody> getTokenRequest(#Query("grant_type") String grant_type,
#Query("client_id") String client_id,
#Query("client_secret") String client_secret,
#Query("email") String email,
#Query("password") String password);
//The call where i use my access_token
#GET("/api/getLanguages")
Call<ResponseBody> getLanguages(#Header("Content-Type") String json,
#Header("Authorization") String token,
#Header("Cache-Control") String cache);}
Here's the retrofit and OkHttpClient initialize part.
public class ApiClient {
private static ApiClient instance;
private SupportopApi supportopApi;
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(#NonNull Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.build();
return chain.proceed(request);
}
});
supportopApi = new Retrofit.Builder()
.baseUrl(endpoint)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(SupportopApi.class);
}
public static synchronized void initializeInstance(String endpoint) {
if (instance == null) {
instance = new ApiClient(endpoint);
}
}
public static synchronized ApiClient getInstance() {
if (instance == null) {
throw new IllegalStateException("PentairAPIClient has not been initialized.");
}
return instance;
}
public Call<ResponseBody> registration(SupportopObjRegistration supportopObjRegistration) {
return supportopApi.registrationRequest(supportopObjRegistration);
}
public Call<ResponseBody> activation(SupportopObjClient activate) {
return supportopApi.clientActivationRequest(activate);
}
public Call<ResponseBody> getToken(String grant_type, String client_id, String client_secret,
String email, String password) {
return supportopApi.getTokenRequest(grant_type, client_id, client_secret, email, password);
}
public Call<ResponseBody> getLanguage(String token) {
String new_token = "Bearer " + token;
return supportopApi.getLanguages("application/json", new_token, "no-cache");
}
}
Registration works great, so I'll show you only the login call.
public class LoginFragment extends BaseFragment {
private View mainView;
private ApiClient apiClient;
private EditText email, password;
private Button userLogin;
private SupportopObjClient supportopClientActivate;
#Override
public String toString() {
return "LoginFragment";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.login_fragment, container, false);
init(mainView);
return mainView;
}
private void init(final View v) {
apiClient = ApiClient.getInstance();
email = (EditText) v.findViewById(R.id.login_email);
password = (EditText) v.findViewById(R.id.login_password);
userLogin = (Button) v.findViewById(R.id.user_login);
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
supportopClientActivate.setUsername("");
supportopClientActivate.setEmail(email.getText().toString());
supportopClientActivate.setPassword(password.getText().toString());
supportopClientActivate.setType("generic");
getClient();
}
});
}
public void getClient() {
Call<ResponseBody> callActive = apiClient.activation(supportopClientActivate);
callActive.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
//Parsing the data from Json to string
String data = response.body().string();
JSONObject obj = new JSONObject(data);
String client_id = obj.getString("client_id");
String client_secret = obj.getString("client_secret");
//Saving clientID and clientSecret in phone storage
SharedPreferencesManager.getInstance().setClientID(client_id);
SharedPreferencesManager.getInstance().setClientSecret(client_secret);
//Calling the tokenCall method to get access token and refresh token
loginCall(client_id, client_secret);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
//if the response not successful
Toast.makeText(getActivity(), "user doesn't exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "An error occurred", Toast.LENGTH_SHORT).show();
}
});
}
public void loginCall(String client_id, final String client_secret) {
Call<ResponseBody> token = apiClient.getToken("password", client_id, client_secret,
supportopClientActivate.getEmail(), supportopClientActivate.getPassword());
token.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
//Parsing the data from Json to string
String dataAccess = response.body().string();
JSONObject obj = new JSONObject(dataAccess);
String access_token = obj.getString("accessToken");
String refresh_token = obj.getString("refreshToken");
Toast.makeText(context, access_token, Toast.LENGTH_SHORT).show();
SharedPreferencesManager.getInstance().setAccessToken(access_token);
SharedPreferencesManager.getInstance().setRefreshToken(refresh_token);
Toast.makeText(context, SharedPreferencesManager.getInstance().getAccessToken(), Toast.LENGTH_SHORT).show();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "password or email are incorrect or doesn't exist",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "An error occurred", Toast.LENGTH_SHORT).show();
}
});
}

how to make generic retrofit library for api calling

i'm working on API integration. i want to make generic class for API integration. which can comfortable with for all API integration.right now i'm using separate code for all API. i'm new in android application development. so please guide me.
public void getHomeCategoryDetailApi(Context context) {
final ProgressDialog loadingDialog = ProgressDialog.show(context, "Please wait", "Loading...");
Retrofit restAdapter = ApiLists.retrofit;
ApiLists apiCall = restAdapter.create(ApiLists.class);
Call<HomeCategoryModelClass> call = apiCall.homePageCatListAPI();
Log.d(TAG, "CategoryDetail : " + call.request()+" \n"+apiCall.homePageCatListAPI().toString());
call.enqueue(new Callback<HomeCategoryModelClass>() {
#Override
public void onResponse(Call<HomeCategoryModelClass> call, Response<HomeCategoryModelClass> response) {
Log.d(TAG, "onResponse: CategoryDetail:" + response.body());
Log.d(TAG, "onResponse: response.code():" + response.code());
if (response.body() == null) {
loadingDialog.dismiss();
globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
} else {
loadingDialog.dismiss();
if (response.body().getStatusCode().equalsIgnoreCase("1")) {
homeCategoryImageMenu = (ArrayList<Menu>) response.body().getMenu();
thirdHorizontalRecyclerAdapter.notifyDataSetChanged();
} else {
globalClass.showAlertDialog(getActivity(), "Alert", "" + response.body().getStatus(), false);
}
}
if (response.errorBody() != null) {
try {
Log.d(TAG, "onResponse: response.errorBody()===>" + response.errorBody().string());
if (loadingDialog.isShowing() && loadingDialog != null) {
loadingDialog.dismiss();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<HomeCategoryModelClass> result, Throwable t) {
Log.d(TAG, "onFailure: " + result.toString());
loadingDialog.dismiss();
globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
}
});
}
Here is Bast Way to call API
public class APIResponse {
private static String TAG = APIResponse.class.getSimpleName();
public static <T> void callRetrofit(Call<T> call, final String strApiName, Context context, final ApiListener apiListener) {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
if (strApiName.equalsIgnoreCase("LoginApi")) {
if (response.isSuccessful()) {
Log.d(TAG, "onResponse: " + response.body().toString());
// NearByNurse nearByNurse = (NearByNurse) response.body(); // use the user object for the other fields
// apiListener.success(url,nearByNurse);
progressDialog.dismiss();
} else {
try {
Log.d(TAG, "onResponse: " + response.errorBody().string());
apiListener.error(strApiName, response.errorBody().string());
progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (strApiName.equalsIgnoreCase("")) {
//Patient user = (Patient) response.body();
}
}
#Override
public void onFailure(Call<T> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.toString());
if (strApiName.equalsIgnoreCase("searchNearbyTest")) {
apiListener.failure(strApiName, t.toString());
}
progressDialog.dismiss();
}
});
}
In API Calling Side
private void loginApi() {
Retrofit retrofit = ApiLists.retrofit;
ApiLists apiList = retrofit.create(ApiLists.class);
Call<JsonElement> loginApiCall = apiList.loginApi("kjdf", "fkldngdkl", "lkfdxngl", "kjngn", "jksdgkj");
APIResponse.callRetrofit(loginApiCall, "LoginApi", LoginActivity.this, this);
}
#Override
public void success(String strApiName, Object response) {
if (strApiName.equals("LoginApi")) {
}
}
#Override
public void error(String strApiName, String error) {
if (strApiName.equals("LoginApi")) {
}
}
#Override
public void failure(String strApiName, String message) {
if (strApiName.equals("LoginApi")) {
}
and interface call on API response.
public interface ApiListener {
void success(String strApiName, Object response);
void error(String strApiName, String error);
void failure(String strApiName, String message);
}
This's my common function basic call Api.java
public class Api {
private void basicCall(Call<DataResponse> call) {
if (call == null) {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
return;
}
call.enqueue(new Callback<DataResponse>() {
#Override
public void onResponse(#NonNull Call<DataResponse> call, #NonNull Response<DataResponse> response) {
int code = response.code();
//Check http ok
if (code == HttpURLConnection.HTTP_OK) {
//Check status
if (response.body().getStatus() == Config.STATUS_OK) {
//Everything's OK
listener.onResponseCompleted(Config.STATUS_OK, response.body().getError(), response.body().getData());
} else {
listener.onResponseCompleted(Config.STATUS_FAILED, response.body().getError(), null);
}
} else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
try {
ErrorResponse error = Api.gson.fromJson(response.errorBody().string(), ErrorResponse.class);
listener.onResponseCompleted(Config.STATUS_401, error.getError(), error.getData());
} catch (IOException e) {
e.printStackTrace();
}
} else {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
}
}
#Override
public void onFailure(#NonNull Call<DataResponse> call, #NonNull Throwable t) {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
}
});
}
//And you can use
public void getProductList(OnResponseCompleted listener) {
this.listener = listener;
Call<DataResponse> call = apiService.getProductList();
basicCall(call);
}
}
//or orther function
This's ApiService.java
public interface ApiInterface {
#POST("product/list")
Call<DataResponse> getProductList();
}
This's OnResponseCompleted.java
public interface OnResponseCompleted {
void onResponseCompleted(int status, String error, Object data);
}
i want to make like this .i just pass some require parameter....
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
// Set Dialog Message
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
if (status != null)
// Set alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_success : R.drawable.ic_fail);
// Set OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Show Alert Message
alertDialog.show();
}
Try this code..
In this code Retrofit object set up done in one class and all api calling into interface..
public class ApiClient {
private final static String BASE_URL = "https://api.github.com";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
after that call the api into api interface..
public interface ApiInterface {
#GET("{affenpinscher}/images")
Call<Product> getProductData(#Path("affenpinscher") String breed);
#GET("getProductDetailByProductId?ProductId=3")
Call<JsonObject> ITEM_DESCRIPTION_RESPONSE_CALL();
#POST("linke")
Call<Response> passJsonData(#Body JsonData jsonData);
#GET("/users/waadalkatheri/repos")
Call<Response> getdata();
}
and when you call api in activity or fragment used below code..
ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<ResponseData> responseCall = apiInterface.getdata();
responseCall.enqueue(new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, retrofit2.Response<ResponseData> response) {
if (response.isSuccessful() && response.body() != null && response != null) {
Toast.makeText(getApplicationContext(), "GetData" + response.body().getLanguage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
Log.d("Errror", t.getMessage());
}
});

Login with retrofit third party lib

http://localhost/shop/api2/login.php?email=xxxx#gmail.com&password=xxxxx
{"success":1,"customer_id":"2","customer_group_id":"0","email":"tanaji#gmail.com"}
private void attemptLogin(final String email, final String password) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://192.168.1.14/shop/api2/")
.build();
LoginApi service = retrofit.create(LoginApi.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
Call<ResponseBody> userCall = service.login(email,password);
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
ResponseBody resp = response.body();
if (resp != null && resp.equals(1)) {
Toast.makeText(MainActivity.this, "Response"+response.body(), Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(in);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
if (response.isSuccessful() && response.body() != null && response.body().getStatus().equalsIgnoreCase("success")) {
.getStatus is not working in my code.
and if success: 1 then its want login and then open to new page.
how to get json resopnse successfully?
Make ResponseBody Model
public class ResponseBody
{
private String customer_group_id;
private String email;
private String success;
private String customer_id;
public String getCustomer_group_id ()
{
return customer_group_id;
}
public void setCustomer_group_id (String customer_group_id)
{
this.customer_group_id = customer_group_id;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getSuccess ()
{
return success;
}
public void setSuccess (String success)
{
this.success = success;
}
public String getCustomer_id ()
{
return customer_id;
}
public void setCustomer_id (String customer_id)
{
this.customer_id = customer_id;
}
#Override
public String toString()
{
return "ClassPojo [customer_group_id = "+customer_group_id+", email =
"+email+", success = "+success+", customer_id = "+customer_id+"]";
}
}
Call Retrofit
Call<ResponseBody> userCall = service.login(email,password);
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.body()!=null)
if(response.body().
getSuccess().contains("1"){
Toast.makeText(MainActivity.this,
"Response"+response.body(), Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this,
ProfileActivity.class);
startActivity(in);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
});

Retrofit Post request

I want to post user credentials to following url
: http://myurl/authenticate
Parameters : login. Type (JSON)
username : string
password : string
"login":{"username": "JohnDoe","password": "eoDnhoJ" }
If success
{
" r e s u l t " : " S u c c e s s " ,
"response": "Users Session ID"
}
Here is my code
public interface APIService {
#POST("/authenticate")
#FormUrlEncoded
Call<Login> savePost(#Field("username") String username,
#Field("password") String password);
}
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://myurl/";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
public class Login {
#SerializedName("username")
#Expose
private String username;
#SerializedName("password")
#Expose
private String password;
//getters and setters
}
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class LoginActivity extends AppCompatActivity {
private EditText usernameEditText,passwordEditText;
private Button button;
private APIService mAPIService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameEditText=(EditText)findViewById(R.id.username);
passwordEditText=(EditText)findViewById(R.id.password);
button=(Button)findViewById(R.id.signup);
mAPIService = ApiUtils.getAPIService();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String uname=usernameEditText.getText().toString();
String pass=passwordEditText.getText().toString();
if(TextUtils.isEmpty(uname)){
Toast.makeText(LoginActivity.this, "Username cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(pass)){
Toast.makeText(LoginActivity.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
if(pass.length()<4){
Toast.makeText(LoginActivity.this, "Password should be greater than four characters", Toast.LENGTH_SHORT).show();
return;
}
sendPost(uname, new StringBuilder(uname).reverse().toString());
}
});
}
public void sendPost(String username, String password) {
mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("Pritish", "post submitted to API." + response.body().toString());
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.e("Pritish", "Unable to submit post to API.");
}
});
}
public void showResponse(String response) {
Log.i("Abbu",response);
}
}
Whenever i submit username and password i get null values,can some body please help me?And how can iget the sessionId.I tried looking for various egs but i am so confsued right now.
Instead of follwing code
#POST("/authenticate")
#FormUrlEncoded
Call<Login> savePost(#Field("username") String username,
#Field("password") String password);
Use this code
#POST("/authenticate")
Call<Login> savePost(#Query("username") String username,
#Query("password") String password);
Step 1: instead of this code
public interface APIService {
#POST("/authenticate")
#FormUrlEncoded
Call<Login> savePost(#Field("username") String username,
#Field("password") String password);
}
Use this code:
public interface APIService {
#POST("/authenticate")
Call<Login> savePost(#Body RequestBody body);
}
Step 2: instead of this code in LoginActivity
public void sendPost(String username, String password) {
mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("Pritish", "post submitted to API." + response.body().toString());
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.e("Pritish", "Unable to submit post to API.");
}
});
}
Change to this code :
public void sendPost(String username, String password) {
HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
String strRequestBody = new Gson().toJson(params);
//create requestbody
final RequestBody requestBody = RequestBody.create(MediaType.
parse("application/json"),strRequestBody);
mAPIService.savePost(requestBody).enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("Pritish", "post submitted to API." + response.body().toString());
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.e("Pritish", "Unable to submit post to API.");
}
});
}
Replace your Login class by following
#SerializedName("result")
#Expose
private String rESULT;
#SerializedName("response")
#Expose
private String response;
public String getRESULT() {
return rESULT;
}
public void setRESULT(String rESULT) {
this.rESULT = rESULT;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
Add ServiceGenerator class :
public class ServiceGenerator {
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(ScalarsConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
public static Retrofit getRetrofit()
{
return builder.client(httpClient.build()).build();
}
}
2.Add interface RetrofitAPI :
public interface RetrofitApi {
#POST("/api/v1/user")
Call<ResponseBody> login(#Body RequestBody loginBody);
}
3.Add method for login in your manager class :
public void retrofitLogin(JSONObject login, final String tag) {
RetrofitApi service = ServiceGenerator.createService(RetrofitApi.class);
Call<ResponseBody> result = service.login(convertJsonToRequestBody(login));
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
retrofitCheckResponse(response, tag);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (t instanceof IOException) {
Log.e("retrofit error", "retrofit error");
sendErrorRetrofit(mContext.getString(R.string.ERROR), 500, tag);
}
}
});
}
Method to convert JSONObject to RequestBody :
private RequestBody convertJsonToRequestBody(JSONObject jsonObject) {
if (jsonObject != null) {
return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
} else {
return null;
}
}
4.Now call your retrofitLogin method :
JSONObject mLoginParams = new JSONObject();
JSONObject mLoginObj = new JSONObject();
mLoginParams.put("username", uname);
mLoginParams.put("password", pass);
mLoginObj.put("appType","mobile");
mLoginObj.put("user", mLoginParams);
volleyRequest.retrofitLogin(mLoginObj, "Login");

Categories

Resources