[英]Rest API with authentication token
I have an android application calling a Rest API with the authentication token, with the following code 我有一个使用身份验证令牌调用Rest API的android应用,代码如下
private void apiCall(){
AsyncHttpClient client = new AsyncHttpClient();
RequestParams param = new RequestParams();
client.addHeader("IDENTITY_KEY",TOKEN);
client.get(URL, param, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
mTextMessage.setText(statusCode);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
mTextMessage.setText(statusCode+"");
}
});
}
the problem is when I run the application it returns 0, WHY? 问题是当我运行应用程序时,它返回0,为什么? URL and TOKEN declared and initialized outside the method.
在方法外声明和初始化的URL和TOKEN。
I would recommend you to use the retrofit library to do that. 我建议您使用改装库来执行此操作。
Let's say your URL base is http://baseurl.com/api and you have to perform a GET request to /login passing the email and password. 假设您的网址库为http://baseurl.com/api,并且您必须通过传递电子邮件和密码来执行对/ login的GET请求。 I am assuming that your API will return a User object as JSON.
我假设您的API将以JSON形式返回User对象。
Api.java Api.java
@GET("login")
Call<LoginResponse> verifyLogin(@Query("email") String email, @Query("password") String password);
Where you need to perform API call do the following 在需要执行API调用的地方执行以下操作
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://baseurl.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<LoginResponse> responseCall = api.verifyLogin("email","password");
responseCall.enqueue(new Callback<ProductResponse>() {
@Override
public void onResponse(Call<ProductResponse> call, Response<ProductResponse> response) {
if (response.isSuccessful()){
//do whatever you need,
}
}
@Override
public void onFailure(Call<ProductResponse> call, Throwable t) {
Toast.makeText(context, "There was an error.", Toast.LENGTH_SHORT).show();
Log.e("error",t.getMessage().toString());
}
});
Note: LoginResponse is a POJO class. 注意:LoginResponse是POJO类。 You have to make a POJO class to perform retrofit actions.
您必须制作一个POJO类来执行改装操作。 It's pretty easy.
很简单 You can learn more about Retrofit from here doc 1 doc 2
您可以从此处了解有关改造的更多信息doc 1 doc 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.