尝试使用android-async-http lib从API web到Android获取json响应

问题描述 投票:0回答:1

我一直在使用android-async-http(http://loopj.com/android-async-http/)lib与android但由于某种原因我无法从服务器捕获响应,我知道服务器接收并做了应该做的事情,但我不能无缘无故地得到答复。

以下是调用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中输入的“enter”,这意味着,从未输入onSuccess,onFailure或onRetry方法。

但我知道服务器收到我的请求,因为服务器日志显示:(例如:email:[email protected],pass:prueba)

"=>"[email protected]", "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 '[email protected]' 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":"[email protected]","auth_token":"dc45800fddee07cf9b300d2765283cb2"}}
android json api android-async-http
1个回答
0
投票

大多数教程已经过时,并尝试使用apache库,但我确实找到了一个工作。

在尝试操作团队树屋教程(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=)我的app键将在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语句中,您可以处理数据。

如果网址不是以“http://”或“https://”开头,则代码将无法获得响应,但应用仍会无错运行

© www.soinside.com 2019 - 2024. All rights reserved.