【问题标题】:Rest API with authentication token带有身份验证令牌的 Rest API
【发布时间】:2018-06-28 14:48:21
【问题描述】:

我有一个使用身份验证令牌调用 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+"");
        }
    });
}

问题是当我运行应用程序时它返回 0,为什么? URL 和 TOKEN 在方法外声明和初始化。

【问题讨论】:

  • 请打印 onFailure 中 Throwable 错误的值。它应该包含有关您遇到的问题的更多详细信息。
  • 我认为我的电脑出了点问题,可能是网络连接或其他问题,我重新启动了我的电脑,问题已经解决,谢谢您的回复

标签: java android rest httpclient


【解决方案1】:

我建议您使用 retrofit 库来执行此操作。

假设您的 URL 基础是 http://baseurl.com/api,您必须向 /login 执行 GET 请求并传递电子邮件和密码。我假设您的 API 将返回一个用户对象作为 JSON。

API.java

@GET("login")
Call<LoginResponse> verifyLogin(@Query("email") String email, @Query("password") String password);

在您需要执行 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());

        }
    });

注意:LoginResponse 是一个 POJO 类。您必须创建一个 POJO 类来执行改造操作。这很容易。你可以从这里了解更多关于改造的信息doc 1doc 2

【讨论】:

    猜你喜欢
    • 2018-11-24
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2018-06-22
    • 2012-12-12
    • 2018-03-25
    • 2016-08-10
    • 2014-02-25
    相关资源
    最近更新 更多