我在发送标头中的令牌并在授权后从网站获取一些信息时遇到问题。
这是我的MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static final String BASE_URL = "https://api.some.some/v1/";
SomeAPI userClient;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
userClient = retrofit.create(SomeAPI.class);
login();
}
private void login() {
Auth login = new Auth("123456", "12345678");
Call<User> call = userClient.login(login);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.code() == 201) {
Toast.makeText(MainActivity.this, response.body().getToken(), Toast.LENGTH_SHORT).show();
token = response.body().getToken();
}
else {
Toast.makeText(MainActivity.this, "Token is not truth :(", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "error!", Toast.LENGTH_SHORT).show();
}
});
}
}
这是我的Some API接口:
public interface SomeAPI {
@POST("token")
Call<User> login(@Body Auth login);
}
Here is my Auth.java:
public class Auth {
private String login;
private String password;
public Auth(String login, String password) {
this.login = login;
this.password = password;
}
}
这是我的User.java:
public class User {
private int id;
private String email;
private String token;
public int getId(){
return id;
}
public void setId(){
this.id = id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getToken(){return token;}
public void setToken(String token){this.token = token;}
public String getfirst_name()
{
return first_name;
}
public void setfirst_name(String first_name) {
this.first_name = first_name;
}
}
所以在这之后,我有了一个令牌,现在我想在其他活动中获得一些信息。
Userprofile.java:
ProstoTVAPI userClient;
String first_name = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
userClient = retrofit.create(ProstoTVAPI.class);
getUserInfo();
}
private void getUserInfo() {
User user = new User();
Call<User> call = userClient.getInfo();
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.code() == 200){
first_name = response.body().getfirst_name();
tvName.setText(first_name);
}
else {
Toast.makeText(UserProfile.this, "First name was not loaded", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(UserProfile.this, "error!", Toast.LENGTH_SHORT).show();
}
});
}
我必须发送获得授权后获得的令牌才能获取新信息,例如first_name = response.body().getfirst_name();
如何通过此活动做到这一点?我需要更改/添加代码吗?
我创建了PreferencesManager来保存我的偏好:
public class PreferencesManager {
private static final String PREFERENCES = "MyPrefs";
private static PreferencesManager instance = null;
private static SharedPreferences sharedPreferences;
public static PreferencesManager getInstance() {
if (instance == null) {
instance = new PreferencesManager();
}
return instance;
}
private static SharedPreferences getSharedPreferences(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
return sharedPreferences;
}
public static void putString(Context context, String key, String value) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value).apply();
}
public static String getString(Context context, String key, String defValue) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
return sharedPreferences.getString(key, defValue);
}
}
因此在获得令牌的活动中,我做了:editor.putString("token", token);
,其中编辑者-SharedPreferences.Editor editor;
在“活动”中,我发送令牌作为标头:
private void getUserInfo() {
User user = new User();
Call<User> call = userClient.getInfo("Bearer " + token);
...
}
和onCreate()中:
editor = getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
token = PreferencesManager.getString(this,"token", null);
我还添加了ApiInterface:
Call<User> getInfo(@Header("Authorization") String token);
答案 0 :(得分:1)
我通过这种方式在标头中发送令牌:-
这是ApiInterface类:-
Call<ReactionResponse> submitReactionPart(@Header("Authorization") String token);
这是活动:-
Call<ReactionResponse> responseCall = apiInterface.submitReactionPart("Bearer " +token);
这是我的偏好claas看看:-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean isUserLoggedOut(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("id_logged_in", true);
}
public static void setUserLoggedOut(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("id_logged_in", value);
mPrefsEditor.commit();
}
public static String getUserImage(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getString("userImage", "");
}
public static void setUserImage(Context ctx, String value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putString("userImage", value);
mPrefsEditor.commit();
}
}
在要使用首选项值的活动中,它将返回字符串值:-
String userImageUrl = AppPreference.getUserImage(MyActivity.class);
在活动中要优先存储值的地方:-
AppPreference.setUserImage(MyActivity.class, "put your value here");
答案 1 :(得分:1)
您可以创建OkHttpClient拦截器,以将令牌标头添加到所有调用中:
private static Response intercept(Interceptor.Chain chain) throws IOException
{
Request.Builder builder = chain.request().newBuilder()
.addHeader("authorization", String.format("%s %s", UserSession.tokenType, UserSession.accessToken));
return chain.proceed(builder.build());
}
然后创建OkHttpClient实例并添加拦截器:
client = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(YourClass::intercept)
.build();
最后,构建您的Retrofit实例:
final Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
只要您的UserSession
类拥有tokenType
和accessToken
,授权标头就会自动添加到所有呼叫中。您可以将UserSession保存到共享的首选项或保存在内存中。