【问题标题】:Trying to get a json response from API web to Android with android-async-http lib尝试使用 android-async-http 库从 API Web 向 Android 获取 json 响应
【发布时间】:2015-03-17 05:27:33
【问题描述】:

我一直在使用带有 android 的 android-async-http (http://loopj.com/android-async-http/) 库,但由于某种原因我无法捕获来自服务器的响应,我知道服务器接收并执行应该做的事情,但我无缘无故得不到回应。

这里是调用 API 的方法:

public User registUser(String mail, String pass) throws UnsupportedEncodingException {
    final User user = new User();
    user.setToken("enter");

    String bodyAsJson = "{\"user\":{\"email\":\""+mail+"\",\"password\":\""+pass+"\"}}";

    StringEntity entity  = new StringEntity(bodyAsJson);
    Header[] headers = {
            new BasicHeader("Content-type", "application/json")
    };

    client.post(this.context, "http://104.131.189.224/api/user", headers , entity, "application/json",  new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
            try {
                json = json.getJSONObject("user");
                user.setId(json.getInt("id"));
                user.setEmail(json.getString("email"));
                user.setPassword("123456");
                user.setToken(json.getString("auth_token"));
            } catch ( JSONException e) {
                user.setToken("not json");
            } catch (Exception e) {
                user.setToken("error ");
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
            user.setToken("comes json array");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            user.setToken(responseString);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            user.setToken("error");
        }

        @Override
        public void onRetry(int retryNo) {
            user.setToken("nothing");
        }
    });

    return user;
}

当我调用该方法时,user.getToken 只显示我在 beginin 中输入的“输入”,也就是说,从未输入过 onSuccess、onFailure 或 onRetry 方法。

但我知道服务器收到了我的请求,因为服务器日志显示: (例如:电子邮件:carlos@prueba.com,传递:prueba)

"=>"carlos@prueba.com", "password"=>"[FILTERED]"}}                              
    D, [2015-03-17T05:15:27.660562 #28450] DEBUG -- :    (0.8ms)  BEGIN
    D, [2015-03-17T05:15:27.671126 #28450] DEBUG -- :   User Exists (2.6ms)  SELECT
    1 AS one FROM `users` WHERE `users`.`email` = BINARY 'carlos@prueba.com' LIMIT
    1
    D, [2015-03-17T05:15:27.677448 #28450] DEBUG -- :   SQL (1.0ms)  INSERT INTO `us
    ers` (`email`, `encrypted_password`, `created_at`, `updated_at`) VALUES ('carlos
    @prueba.com', '$2a$10$Dg358IzoaG5KVJ8ZJTeViev2v5B9CAnAqIYI1Zd4EIFC.0Mh.nMU6', '2
    015-03-17 05:15:27.672898', '2015-03-17 05:15:27.672898')                       
    D, [2015-03-17T05:15:27.681514 #28450] DEBUG -- :    (2.0ms)  COMMIT
    D, [2015-03-17T05:15:27.684634 #28450] DEBUG -- :   User Exists (0.6ms)  SELECT
    1 AS one FROM `users` WHERE `users`.`auth_token` = '6aff3b4162cfcf3062a6db12a1c
    ee2bc' LIMIT 1                                                                  
    D, [2015-03-17T05:15:27.685582 #28450] DEBUG -- :    (0.2ms)  BEGIN
    D, [2015-03-17T05:15:27.690901 #28450] DEBUG -- :   SQL (0.8ms)  UPDATE `users`
    SET `auth_token` = '6aff3b4162cfcf3062a6db12a1cee2bc', `updated_at` = '2015-03-1
    7 05:15:27.687516' WHERE `users`.`id` = 11                                      
    D, [2015-03-17T05:15:27.693809 #28450] DEBUG -- :    (1.8ms)  COMMIT
    I, [2015-03-17T05:15:27.698987 #28450]  INFO -- :   Rendered api/users/_user.jso
    n.jbuilder (0.3ms)
    I, [2015-03-17T05:15:27.700292 #28450]  INFO -- :   Rendered api/users/create.js
    on.jbuilder (3.2ms)
    I, [2015-03-17T05:15:27.701395 #28450]  INFO -- : Completed 200 OK in 223ms (Vie
            ws: 6.3ms | ActiveRecord: 10.0ms)

服务器应以以下格式响应 json:

{"user":{"id":3,"email":"carlos@prueba.com","auth_token":"dc45800fddee07cf9b300d2765283cb2"}}

【问题讨论】:

  • 从服务器端提供代码。
  • 我没有来自服务器端的代码,但是让我问一下我能不能得到它服务器响应为 200 代码,那么为什么从不在我的代码中输入某些 onSuccess 方法?
  • 为了澄清您的错误,我建议您尝试 (1) AsyncHttpResponseHandler 而不是 JsonHttpResponseHandler。检查服务器响应更为原始。 (2)使用Fiddler查看实际的http通信。它是调试 http 通信的绝佳工具。
  • 一样,从来没有进入过onScucess或者其他方法

标签: android json api android-async-http


【解决方案1】:

大多数教程都已过时并尝试使用 apache 库,但我确实找到了一个可行的。

在尝试操作 Team Treehouse 教程 (https://teamtreehouse.com/library/build-a-weather-app/) 以使用事件查找器 api 而不是他们的天气 api 时,我遇到了同样的问题。

他们使用 OkHttp 库

  1. 将 OkHttp 库编译到 Module:app 下的 build.gradle 文件中

compile 'com.squareup.okhttp:okhttp:2.4.0'

这是截至 2015 年 7 月 9 日的最新版本

  1. 访问 api url 以查看您是否确实在检索数据并且它的格式是否正确。对我来说,我使用 Eventful.com 并查找我所在地区的活动。 (https://api.eventful.com/json/events/search?l=arizona&within=15&units=miles&app_key=) 我的应用程序密钥将在 url 末尾的“=”之后。

此时一切正常,现在我需要添加 OkHttp 代码来下载 json 数据

  1. 为您的清单添加互联网权限

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.thestephenmiller.myApp" > <uses-permission android:name="android.permission.INTERNET" /> </manifest>

  1. 打开将发出请求的类或活动并添加以下代码。

String eventfulUrl = "https://api.eventful.com/json/events/search?l=arizona&within=15&units=miles&app_key="+apiKey; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(eventfulUrl) .build();

然后拨打电话

` 
Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                if (response.isSuccessful()) {
                    Log.v(TAG, response.body().string());
                }
            } catch (IOException e) {
                Log.e(TAG, "Exception Caught: ", e);
            }
        }
    });

全部添加到onCreate()

这一行 Log.v(TAG, response.body().string()); 是将响应输出到日志的内容,并且在您可以处理数据的 if 语句中。

如果 url 不以“http://”或“https://”开头,则代码将不会得到响应,但应用仍会无错误地运行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2022-06-28
    • 2018-12-11
    • 2020-02-03
    相关资源
    最近更新 更多