【问题标题】:get android AsyncHttpClient response after it finish完成后获取android AsyncHttpClient响应
【发布时间】:2016-03-21 23:23:41
【问题描述】:

您好,我正在使用AsyncHttpClientrestful api 发送请求 问题是我想在onSuccess 中获得结果并将其从拥有此方法的班级传递给我的活动

public int send(JSONObject parameters,String email,String password){
      int i =0;
    try {
        StringEntity entity = new StringEntity(parameters.toString());
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        client.setBasicAuth(email,password);
        client.post(context, "http://10.0.2.2:8080/webapi/add", entity, "application/json",
                new AsyncHttpResponseHandler() {


                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        try {
                            JSONObject json = new JSONObject(
                                    new String(responseBody));
                            i=statusCode;
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                    }
                });


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
return i;
}

当然,我总是得到i=0;因为它是Async 方法 我试图让方法发送void 并在 onSuccess 内部进行回调,但这会导致活动出现很多问题(这是我稍后会问的另一个问题) 那么你有办法将 i 的值作为 statusCode 吗? 谢谢。

【问题讨论】:

    标签: android rest android-async-http


    【解决方案1】:

    我试图让方法发送无效并在 onSuccess 内部进行回调

    无效的方法是好的。

    在 onSuccess 内部进行回调可能如下所示

    添加回调接口

    public interface Callback<T> {
        void onResponse(T response);
    }
    

    将其用作参数并使方法无效

    public void send(
        JSONObject parameters, 
        String email,
        String password, 
        final Callback<Integer> callback) // Add this
    

    然后,在onSuccess 方法中,当你得到结果时做

    if (callback != null) {
        callback.onResponse(statusCode);
    }
    

    在调用send的方法之外,创建匿名回调类

    webServer.send(json, "email", "password", new Callback<Integer>() {
        public void onResponse(Integer response) {
            // do something
        }
    });
    

    【讨论】:

    • 欢迎。不过,不确定您为什么要返回响应代码。你应该返回 JSONObject 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多