How to send Token in Header to server in Android - android

In my application I want to create a Login/Register page.
In the login page I send the Username, Password, Token from client to Server.
I should get Username and Password from USER, and get Token from HEADER of Request.
For connect client to server I use Retorfit 2.2.0 library.
Code from the Interface class :
#POST("User/Authenticate")
Call<LoginResponse> getLoginResponse(#Header("Token") String token, #Body LoginDatum loginDatum);
Code within the Activity :
public void getLogin(String username, String password) {
final LoginDatum loginDatum = new LoginDatum();
loginDatum.setUsername(username);
loginDatum.setPassword(password);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum);
Log.e("tokenTAG", "Token : " + sendToken);
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
String token = response.headers().get("Token");
if (token != null) {
sendToken = token;
Log.e("tokenTAG", "Token : " + sendToken);
}
if (loginResponse.getStatusCode() == 200) {
Toasty.success(context, context.getResources().getString(R.string.welcome) + " " +
loginResponse.getData().getName(), Toast.LENGTH_LONG, true).show();
} else {
Toasty.error(context, loginResponse.getStatusMessage() + "", Toast.LENGTH_LONG, true).show();
}
loadProgress.get(0).setVisibility(View.GONE);
loginBtn.setVisibility(View.VISIBLE);
btnShadow.setVisibility(View.VISIBLE);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
loadProgress.get(0).setVisibility(View.GONE);
loginBtn.setVisibility(View.VISIBLE);
btnShadow.setVisibility(View.VISIBLE);
Toasty.error(context, context.getResources().getString(R.string.failRequest),
Toast.LENGTH_LONG, true).show();
}
});
}
And show me this in LogCat :
tokenTAG: Token : null
tokenTAG: Token : MKGKFPOVRMU4MRK0STNDO20RA2MPEWT7Y1N2WUM5QLIXJX2TEOM9APGUTYJMD8R42WFVESD8GRXCTCINA2LZKU7JV2I7KA2R4N5W
But when I want to send the token with this code : Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum); it shows me null.
I have use this line : Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum); to generate the request callBack, although this line Token is not NUll.
How can I fix it?

if you use Retrifit get onNetwork request,in order to add Header to your requese,you must be write an Intercepter.

just replace getClient menthod with this one
public static Retrofit getClient(final Context context) {
if (retrofit == null) {
Log.d("AuthTokenTest", "getClient: null");
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
dispatcher = new Dispatcher();
httpClient.dispatcher(dispatcher);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Log.d("INTERCEPTOR", original.url().toString());
//System.out.print(original.toString());
Request request;
user=User.getLoggedInUserInstance(context);
String authToken="";
if(user!=null)
authToken=user.getAuthToken();
Log.d("AuthTokenTest", "intercept: authtoken:"+authToken);
request = original.newBuilder()
.header("X-AUTH-TOKEN", authToken)
.header("x-requested-with", "XMLHttpRequest")
.method(original.method(), original.body())
.build();
okhttp3.Response response = chain.proceed(request);
Log.d("INTERCEPTOR-", "response_code: "+response.code());
// Log.d("INTERCEPTOR", response.body().string());
return response;
}
});
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
if(BuildConfig.DEBUG){
//print the logs in this case
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}else{
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
httpClient.addInterceptor(loggingInterceptor);
OkHttpClient client = httpClient.build();
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
let me know if this solution works or not

Related

Android RetroFit: 400 Response

I am plugging Retrofit into my android app.
Here is how I build retrofit, notice the interceptor for the logging and headers.
public void buildRetrofit(String token){
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addNetworkInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.header("Authorization", "Bearer " + token)
.header("Content-Type", "application/json")
.header("api-version", "1")
.method(chain.request().method(), chain.request().body())
.build();
return chain.proceed(newRequest);
}
});
httpClient.addInterceptor(logging);
Retrofit.Builder buidler = new Retrofit.Builder()
.baseUrl("XXX_HIDDEN_FORSTACKOVERFLOW")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build());
retroFit = buidler.build();
}
I make the call like so
OrderApi orderApi = mainActivity.retroFit.create(OrderApi.class);
Call<Order> call = orderApi.getOpenOrder();
call.enqueue(new Callback<Order>() {
#Override
public void onResponse(Call<Order> call, Response<Order> response) {
Order a = response.body();
int b = 1;
}
#Override
public void onFailure(Call<Order> call, Throwable t) {
}
});
And here is how the actual request tag
public interface OrderApi {
#POST("/HIDDEN")
Call<Order> getOpenOrder();
}
Lastly, here is the order class
public class Order {
private String orderId;
private OrderStatus orderStatus;
public String getOrderId(){
return orderId;
}
public OrderStatus getOrderStatus() {
return orderStatus;
}
}
I get a response of 400. I have no idea why, and It works in postman etc. Something to note is that the response contains a lot more properties than just the ones in the class. I just want a proof on concept, but that shouldn't break things right?
.................
Managed to fix it. Had to send an empty body request as it was a post but I wasn't posting anything. API is dumb.
See here to send empty request Send empty body in POST request in Retrofit

more than one requested posted to server (retrofit)

I am using retrofit to post the request to server but it is posting data twice. I have checked code, I made only on call. I know retrofit trying to connect server again and again until it connected or timeout but if once data posted to server and I get the response from server than why retrofit making again call for the same.
Call<LoanSaveResponse> call = apiService.saveLoan(loan);
call.enqueue(new retrofit2.Callback<LoanSaveResponse>() {
#Override
public void onResponse(Call<LoanSaveResponse> call, Response<LoanSaveResponse> response) {
customProgressBar.stopProgressBar();
Log.e(" response", new Gson().toJson(response));
if (response != null) {
if (response.body() != null) {
// Showing Alert Message
showDialog(response.body().loan_id);
}
}
}
#Override
public void onFailure(Call<LoanSaveResponse> call, Throwable t) {
customProgressBar.stopProgressBar();
Log.e("Failed", t.toString());
}
});
}
public class ApiClient {
/*http://172.16.40.1:8080/loyalty/*/
//:http://54.83.7.62:8080/loyalty/userAnswer
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(GlobalBaseUrl.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
}
For Retrofit 2
Define a listener in your web service instance:
public interface OnConnectionTimeoutListener {
void onConnectionTimeout();
}
Add an interceptor to your web service:
public WebServiceClient() {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
return onOnIntercept(chain);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
webService = retrofit.create(WebService.class);
}
Enclose your intercept code with the try-catch block and notify the listener when an exception happens:
private Response onOnIntercept(Chain chain) throws IOException {
try {
Response response = chain.proceed(chain.request());
String content =
UtilityMethods.convertResponseToString(response);
Log.d(TAG, lastCalledMethodName + " - " + content);
return;
response.newBuilder().body
(ResponseBody.create
(response.body().contentType(), content))
.build();}
catch (SocketTimeoutException exception) {
exception.printStackTrace();
if(listener != null)
listener.onConnectionTimeout();
}
return chain.proceed(chain.request());
}

Using Interceptors to customize header in Retrofit calls

I am trying to use an Interceptor to add a header when using Retrofit. I think I have created my Interceptor in the right way but I don't know what should I do to call it and connect it with my GET Retrofit method.
This is my Interceptor:
public class HeaderInterceptor
implements Interceptor {
#Override
public Response intercept(Chain chain)
throws IOException {
Request request = chain.request();
request = request.newBuilder()
.addHeader(Constants.VersionHeader.NAME, Constants.VersionHeader.VALUE)
.addHeader("Authorization", "Bearer " + token)
.addHeader("Origin","MY URL")
.build();
Response response = chain.proceed(request);
return response;
}
}
And this is my interface:
public interface CategoryService {
#GET("/v3/projects/{projectId}/categories/")
Call<ArrayList<Category2>> getProjectCategories(#Path("projectId") String projectId);
}
I also have this client which I don't know if I should use it anymore considering that I am using an Interceptor:
public class CategoryClient {
public static final String BASE_URL = "MY URL";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
So I have this GET method getProjectCategories, where I pass the projectID and it returns the contents. What I want to know is how can I call the method using the Interceptor and be able to get the results from the request.
I was able to fix my problem by creating a method called SendNetworkRequest sending the projectId as a parameter, and inside this class I created my OkHttpClient, my Interceptor and my retrofit builder to handle everything that i needed.
private void SendNetworkRequest(String projectID) {
OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();
okhttpBuilder.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newRequest = request.newBuilder().header("Authorization", "Bearer " + token);
return chain.proceed(newRequest.build());
}
});
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("MY URL")
.client(okhttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
CategoryService category = retrofit.create(CategoryService.class);
Call<ArrayList<Category2>> call = category.getProjectCategories(projectID, token);
call.enqueue(new Callback<ArrayList<Category2>>() {
#Override
public void onResponse(Call<ArrayList<Category2>> call, Response<ArrayList<Category2>> response) {
listCategories = response.body();
listCategories.remove(response.body().size() - 1);
if (response.body().size() > 0){
add_category_layout.setVisibility(View.VISIBLE);
layout_bar.setVisibility(View.VISIBLE);
message_body.setVisibility(View.INVISIBLE);
message_title.setVisibility(View.INVISIBLE);
edit_image.setVisibility(View.INVISIBLE);
adapter2 = new CategoryAdapter2(getApplicationContext(), listCategories);
recyclerView.setAdapter(adapter2);
recyclerView.setVisibility(View.VISIBLE);
}
}
#Override
public void onFailure(Call<ArrayList<Category2>> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}

android retrofit post logout request giving error 406 Not Acceptable : User is not logged in. ...on postman api works fine

I am using retrofit2 to logout in App but everytime it gives error406
: Not Acceptable : User is not logged in. . i am using retrofit custom
header authentication . Here is my Code :
logout code
public void logout()
{
Log.v("checkTokenbefore",Constants.token);
OkHttpClient httpClient1 = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Log.v("checkLogin",Constants.token+Constants.username+Constants.password) ;
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept-Language","application/json").addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")
.addHeader("X-CSRF-Token",Constants.token)
;
Request request = requestBuilder.method(original.method(),original.body()).build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit1 = new Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.client(httpClient1)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface restAPI1 = retrofit1.create(ApiInterface.class);
Call<Logout> callLogout = restAPI1.userLogout(Constants.token,Constants.username,Constants.password);
callLogout.enqueue(new Callback<Logout>() {
#Override
public void onResponse(Call<Logout> call, retrofit2.Response<Logout> response) {
Log.v("responseLogout",response.code()+"code"+response.errorBody().toString()+response.message()) ;
}
#Override
public void onFailure(Call<Logout> call, Throwable t) {
}
});
}
While Following is the code for login which works fine :
public void loginQuestin(){
//checkValidation ();
/*
ApiInterface apiService =
ApiClient.create(ApiInterface.class) ;*/
ApiInterface restAPI = retrofit.create(ApiInterface.class);
Call<UserAgain> call = restAPI.userLogin(mEmailAddress.getText().toString().trim(),
mPassword.getText().toString().trim());
call.enqueue(new Callback<UserAgain>() {
#Override
public void onResponse(Call<UserAgain> call, Response<UserAgain> response) {
Log.v("check",response.code()+"login"+response.body().getToken()) ;
//response.body().getU
Constants.username = mEmailAddress.getText().toString().trim() ;
Constants.password = mPassword.getText().toString().trim() ;
if (response.code()==200) {
Log.v("checkAgain",response.code()+"login") ;
Constants.token = response.body().getToken() ;
startActivity(new Intent(LoginActivity.this, NavigationDrawerActivity.class));
}
}
#Override
public void onFailure(Call<UserAgain> call, Throwable t) {
Log.v("check","failed");
t.printStackTrace();
}
});
}
//API/Http client for login api call
public class ApiClient {
public static OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder() .addHeader("Accept-Language","application/json")
.addHeader("content-type", "application/x-www-form-urlencoded").addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")
;
Request request = requestBuilder.build();
return chain.proceed(request);
}
}).build();
public static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
public static ApiInterface restAPI = retrofit.create(ApiInterface.class);
}
API Interface class
#POST("token")
Call<Token> getToken();
#FormUrlEncoded
#POST("login")
Call<UserAgain> userLogin(#Field("username") String param1, #Field("password") String param2);
#FormUrlEncoded
#POST("logout")
Call<Logout> userLogout(#Field("username") String param1 , #Field("password") String param2);
Login APi works fine give a response code of 200 OK . The major issue is encountered when working with added dynamic customn header on logout api (client xsrf token )
Reference :
https://futurestud.io/tutorials/retrofit-add-custom-request-header
api formats :
User Authentication/Login
Purpose: - User Login Rest URL: - /api/v1/people/login
Method:-POST Headers: Accept-Language: application/json API_KEY:
a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded
X-CSRF-Token:
User Logout
Purpose: - User Logout Rest URL: - /api/v1/people/logout
Method:-POST Headers: Accept-Language: application/json API_KEY:
a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded
X-CSRF-Token: Parameters in body: username: e.g
service#test.com password: e.g. 123456
Use Interceptors for adding dynamic Header.
httpClient.addInterceptor((Interceptor.Chain chain) -> {
Request originalRequest = chain.request();
set OAuth token
Request.Builder newRequest = originalRequest.newBuilder();
newRequest.header("Authorization", accessToken).method(originalRequest.method(), originalRequest.body());
originalRequest = newRequest.build();
chain.proceed(originalRequest);
repeat request with new token
Response response = chain.proceed(originalRequest); //perform request, here original request will be executed
if (response.code() == 401) {
//if unauthorized
//perform all 401 in sync blocks
}
return chain.proceed(newRequest.build());
});

Retrofit 2 Posting with apikey?

This is my interface:
public interface ApiInterface {
#GET("solicitation/all")
Call<SolicitationResponse> getAllNews(#Query("X-Authorization") String apiKey);
#POST("solicitation/create ")
Call<Solicitation> createSolicitation(#Body Solicitation solicitation);
}
And this is the MainActivity code to create a new solicitation:
Solicitation solicitation = new Solicitation("xx", "list", "31", "32", "description goes here", "file goes here", "userid goes here", "203120312");
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Solicitation> call = apiService.createSolicitation(solicitation);
call.enqueue(new Callback<Solicitation>() {
#Override
public void onResponse(Call<Solicitation> call, Response<Solicitation> response) {
Log.d("Response::", "Success!");
}
#Override
public void onFailure(Call<Solicitation> call, Throwable t) {
Log.e("Response::", "Fail!!");
}
});
The problem is, as you've seen above on the query I use an api key. #Query("X-Authorization").
It seems I can't do the same to the #Body.
Is there a way to insert the api key there like in the query?
just add the Query separate by comma
Call<Solicitation> createSolicitation(#Query("X-Authorization") String apiKey, #Body Solicitation solicitation);
or in header
Call<Solicitation> createSolicitation(#Header("X-Authorization") String apiKey, #Body Solicitation solicitation);
or you need an interceptor to insert the header
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("X-Authorization", "YOUR AUTH KEY"); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
usage
Call<Solicitation> call = apiService.createSolicitation("YOUR API KEY",solicitation);

Categories

Resources