如何在 Java 中将不记名令牌添加到改装请求
How to add bearer token to retrofit request in Java
嗨,我正在尝试向 java 中的改造调用添加不记名令牌,但我似乎无法通过它。
目前我使用一种方法登录,这会创建一个不记名令牌,我正在尝试将令牌添加到 Get Call,但它只是返回 401 错误,我是否已将令牌正确添加到调用中?
@GET("diagnosis/configuration")
Call<ResponseBody> getFavourites (@Query("favourite") Boolean fave,@Header("Bearer Token") String authHeader);
@POST("auth/login")
Call<LoginResponse> postLogin (@Body LoginCredentialsBody body);
public class LoginApiStepDefinition extends TestBaseFix {
Retrofit retrofit = super.buildRetrofit(super.buildOkHttpClient());
RetrofitCallsLogin call = retrofit.create(RetrofitCallsLogin.class);
RetrofitCallsGetFavourites favecall = retrofit.create(RetrofitCallsGetFavourites.class);
private Response<LoginResponse> responseBody;
private String favouritesResponseBody;
String usernameValue;
String passwordValue;
@And("I login with {string} and {string} to return login token")
public void iLoginWithAndToReturnLoginToken(String username, String password) throws Exception {
LoginApi(username, password);
}
public String LoginApi(String username, String password) throws Exception {
usernameValue = username;
passwordValue = password;
//gets fixture ids for the dates
LoginCredentialsBody login = new LoginCredentialsBody();
login.setPassword(passwordValue);
login.setUsername(usernameValue);
String responseBody = call.postLogin(login).execute().body().toString();
String requiredString = responseBody.substring(responseBody.indexOf("=") + 1, responseBody.indexOf(","));
System.out.println(requiredString);
return token;
}
@Then("I get the list of favourites with {string} and {string}")
public void iGetTheListOfFavouritesWithAnd(String username, String password) throws Exception {
String favouritesResponseBody = favecall.getFavourites(true, LoginApi(username, password)).execute().body().toString();
System.out.println(favouritesResponseBody);
}
}
要在改造中添加不记名令牌,您必须创建一个 class 来实现 Interceptor
public class TokenInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
//rewrite the request to add bearer token
Request newRequest=chain.request().newBuilder()
.header("Authorization","Bearer "+ yourtokenvalue)
.build();
return chain.proceed(newRequest);
}
}
现在将您的拦截器 class 添加到 OKHttpClient 对象中,并将该对象添加到 Retrofit 对象中:
TokenInterceptor interceptor=new TokenInterceptor();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("add your url here")
.addConverterFactory(JacksonConverterFactory.create())
.build();
这三个 class 将是您对所有类型的呼叫的最终设置
for first call(Login) you do not need to pass token and after login pass jwt as bearer token to authenticate after authentication do not need to pass
public class ApiUtils {
private static final String BASE_URL="https://abcd.abcd.com/";
public ApiUtils() {
}
public static API getApiService(String token){
return RetrofitClient.getClient(BASE_URL,token).create(API.class);
}}
2.Using ApiUtils.getapiService 你可以获取客户端,通过 jwt 或 bearer token
public class RetrofitClient {
public static Retrofit retrofit=null;
public static Retrofit getClient(String baseUrl, String token){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60,TimeUnit.SECONDS)
.connectTimeout(60,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.addInterceptor(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
}).build();
if(retrofit==null||token!=null){
retrofit= new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}}
3 在此接口中,您可以为 get 或 post 请求创建方法
public interface API {
@POST("/Api/Authentication/Login")
Call<JsonObject> login(@Body Model userdata);
@POST("/api/Authentication/ValidateSession")
Call<JsonObject> validateSession(@Body MyToken myToken);
@POST("/api/master/abcd")
Call<JsonObject> phoneDir(@Body JsonObject jsonObject);
@Multipart
@POST("/api/dash/UploadProfilePic")
Call<JsonObject> uploadProfile(@Part MultipartBody.Part part);
@FormUrlEncoded
@POST("/api/dashboard/RulesAndPolicies")
Call<JsonObject> rulesAndProcess(@Field("ct") int city);
@FormUrlEncoded
@POST("/api/dashboard/RulesAndPolicies")
Call<JsonObject> rulesAndProcess(
@Field("city") int city,
@Field("department") String department,
@Field("ctype") String ctype
);
嗨,我正在尝试向 java 中的改造调用添加不记名令牌,但我似乎无法通过它。
目前我使用一种方法登录,这会创建一个不记名令牌,我正在尝试将令牌添加到 Get Call,但它只是返回 401 错误,我是否已将令牌正确添加到调用中?
@GET("diagnosis/configuration")
Call<ResponseBody> getFavourites (@Query("favourite") Boolean fave,@Header("Bearer Token") String authHeader);
@POST("auth/login")
Call<LoginResponse> postLogin (@Body LoginCredentialsBody body);
public class LoginApiStepDefinition extends TestBaseFix {
Retrofit retrofit = super.buildRetrofit(super.buildOkHttpClient());
RetrofitCallsLogin call = retrofit.create(RetrofitCallsLogin.class);
RetrofitCallsGetFavourites favecall = retrofit.create(RetrofitCallsGetFavourites.class);
private Response<LoginResponse> responseBody;
private String favouritesResponseBody;
String usernameValue;
String passwordValue;
@And("I login with {string} and {string} to return login token")
public void iLoginWithAndToReturnLoginToken(String username, String password) throws Exception {
LoginApi(username, password);
}
public String LoginApi(String username, String password) throws Exception {
usernameValue = username;
passwordValue = password;
//gets fixture ids for the dates
LoginCredentialsBody login = new LoginCredentialsBody();
login.setPassword(passwordValue);
login.setUsername(usernameValue);
String responseBody = call.postLogin(login).execute().body().toString();
String requiredString = responseBody.substring(responseBody.indexOf("=") + 1, responseBody.indexOf(","));
System.out.println(requiredString);
return token;
}
@Then("I get the list of favourites with {string} and {string}")
public void iGetTheListOfFavouritesWithAnd(String username, String password) throws Exception {
String favouritesResponseBody = favecall.getFavourites(true, LoginApi(username, password)).execute().body().toString();
System.out.println(favouritesResponseBody);
}
}
要在改造中添加不记名令牌,您必须创建一个 class 来实现 Interceptor
public class TokenInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
//rewrite the request to add bearer token
Request newRequest=chain.request().newBuilder()
.header("Authorization","Bearer "+ yourtokenvalue)
.build();
return chain.proceed(newRequest);
}
}
现在将您的拦截器 class 添加到 OKHttpClient 对象中,并将该对象添加到 Retrofit 对象中:
TokenInterceptor interceptor=new TokenInterceptor();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("add your url here")
.addConverterFactory(JacksonConverterFactory.create())
.build();
这三个 class 将是您对所有类型的呼叫的最终设置
for first call(Login) you do not need to pass token and after login pass jwt as bearer token to authenticate after authentication do not need to pass
public class ApiUtils {
private static final String BASE_URL="https://abcd.abcd.com/";
public ApiUtils() {
}
public static API getApiService(String token){
return RetrofitClient.getClient(BASE_URL,token).create(API.class);
}}
2.Using ApiUtils.getapiService 你可以获取客户端,通过 jwt 或 bearer token
public class RetrofitClient {
public static Retrofit retrofit=null;
public static Retrofit getClient(String baseUrl, String token){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60,TimeUnit.SECONDS)
.connectTimeout(60,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.addInterceptor(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
}).build();
if(retrofit==null||token!=null){
retrofit= new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}}
3 在此接口中,您可以为 get 或 post 请求创建方法
public interface API {
@POST("/Api/Authentication/Login")
Call<JsonObject> login(@Body Model userdata);
@POST("/api/Authentication/ValidateSession")
Call<JsonObject> validateSession(@Body MyToken myToken);
@POST("/api/master/abcd")
Call<JsonObject> phoneDir(@Body JsonObject jsonObject);
@Multipart
@POST("/api/dash/UploadProfilePic")
Call<JsonObject> uploadProfile(@Part MultipartBody.Part part);
@FormUrlEncoded
@POST("/api/dashboard/RulesAndPolicies")
Call<JsonObject> rulesAndProcess(@Field("ct") int city);
@FormUrlEncoded
@POST("/api/dashboard/RulesAndPolicies")
Call<JsonObject> rulesAndProcess(
@Field("city") int city,
@Field("department") String department,
@Field("ctype") String ctype
);