我需要在我的请求中添加Authorization Header,它必须如下所示:
"Authorization: Basic Zm9vOmJhcg=="
我有我的用户名和密码的价值,如何在Retrofit 2
中添加此请求?这看起来很简单,但我不知道我可以在片段中初始化这个标题?
我的片段类:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
String username_value,password_value;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button) rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize() {
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
username_value = username.getText().toString();
password_value = password.getText().toString();
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
@Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
SignInResults results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
@Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
我的API界面:
public interface VideoApi {
@GET("/videos/featured")
Call<Videos> getFeaturedVideo();
@GET("/videos/new")
Call<Videos> getNewVideo();
@Headers("Content-Type:application/x-www-form-urlencoded")
@FormUrlEncoded
@POST("/auth/create")
Call<SignInResults>insertUser(@Field("email") String username,
@Field("password") String password
);
}
答案 0 :(得分:2)
根据用例,您可以采用两种方法。
第一种方式:使用okhttp客户端
为您的请求添加拦截器final String myToken = "Zm9vOmJhcg==";
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Basic " + yourtoken).build();
return chain.proceed(newRequest);
}
};
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
OkHttpClient client = builder.build();
现在改变你的改装电话。
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.client(client)
.build();
第二种方式:在API调用中添加标题
Call<SignInResults>insertUser(
@Header("Authorization") String token,
@Field("email") String username,
@Field("password") String password
);