Android volley中处理多个请求

2023-12-14

我正在尝试使用 Volley 处理多个请求,并且我收到了所有请求的响应。我的问题是如何识别响应属于哪个API。

mQueue = CustomVolleyRequest.getInstance(this.getApplicationContext())
            .getRequestQueue();

    final CustomJSONObjectrequest jsonRequest = new CustomJSONObjectrequest(Request.Method
            .GET, url,
            new JSONObject(), this, this); // 
    jsonRequest.setTag(REQUEST_TAG);

    final CustomJSONObjectrequest jsonRequest2 = new CustomJSONObjectrequest(Request.Method
            .GET, url2,
            new JSONObject(), this, this);
    jsonRequest2.setTag(REQUEST_TAG);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mQueue.add(jsonRequest);
            mQueue.add(jsonRequest2); // Both the request will have different API request
        }
    });
}
@Override
public void onErrorResponse(VolleyError error) {
    mTextView.setText(error.getMessage());
}

@Override
public void onResponse(Object response) {

    // How to identify, which response is belong to which api request
    mTextView.setText("Response is: " + response);

}

创建一个 Generic Volley 类和一个接口,使用该接口来获取成功和失败响应。

  • 步骤 1 创建一个单独的 Volley 类
  • 步骤 2 创建一个接口来访问 volley 类的响应
  • 步骤 3 创建新对象 类并发送所需参数

new Post VolleyJson Request(TestVolley.this, TestVolley.this(interface), "提交", url, params);

  1. 班级背景
  2. 发送成功和失败响应的接口
  3. 成功时识别的请求类型
  4. 网址(必填)
  5. GET 不需要的参数(可选)

普通截击类

public class PostVolleyJsonRequest {
private String  type;
private Activity act;
private VolleyJsonRespondsListener volleyJsonRespondsListener;
private String networkurl;
private JSONObject jsonObject = null;
private JSONObject params;


public PostVolleyJsonRequest(Activity act, VolleyJsonRespondsListener volleyJsonRespondsListener, String type, String netnetworkUrl,JSONObject params) {
    this.act = act;
    this.volleyJsonRespondsListener = volleyJsonRespondsListener;
    this.type = type;
    this.networkurl = netnetworkUrl;
    this.params = params;
    sendRequest();
}

private void sendRequest() {

    Log.d("url", "url" + networkurl);
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,networkurl,params,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("response", "response " + response);
                    volleyJsonRespondsListener.onSuccessJson(response, type);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    try {
                        NetworkResponse response = error.networkResponse;
                        Log.e("response", "response " + response);
                        if (response != null) {
                            int code = response.statusCode;

                            String errorMsg = new String(response.data);
                            Log.e("response", "response" + errorMsg);
                            try {
                                jsonObject = new JSONObject(errorMsg);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String msg = jsonObject.optString("message");
                            volleyJsonRespondsListener.onFailureJson(code, msg);
                        } else {
                            String errorMsg = error.getMessage();
                            volleyJsonRespondsListener.onFailureJson(0, errorMsg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

    jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
            600000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    RequestQueue requestqueue = Volley.newRequestQueue(act);
    requestqueue.add(jsObjRequest);

}

}

使用接口获取响应消息

public interface VolleyJsonRespondsListener {

public void onSuccessJson(JSONObject result, String type);
public void onFailureJson(int responseCode, String responseMessage);

}

在您想要包含多个请求的班级中

public class TestVolley extends AppCompatActivity implements VolleyJsonRespondsListener{

//Your class code goes here


//network request

try {
        //parameters 
        //Context,Interface,Type(to indentify your responds),URL,parameter for your request 

        //request 1
        new PostVolleyJsonRequest(TestVolley.this, TestVolley.this, "Submit", url, params);

        //request 2
        new PostVolleyJsonRequest(TestVolley.this, TestVolley.this, "AccessData", url_2, params_2);




 } catch (Exception e) {

 e.printStackTrace()
 }

 //Methods from Interface

  @Override
public void onSuccessJson(JSONObject result, String type) {

   //Based on the Type you send get the responds and parse it 
    switch (type) {
        case "Submit":
            try {
                parseSubmit(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case "AccessData":
            try {
                parseAccessData(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
           break;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android volley中处理多个请求 的相关文章

随机推荐

  • ImageView圆角[重复]

    这个问题在这里已经有答案了 我希望图像有圆角 我实现了这个 xml 代码并在我的图像视图中使用它 但图像与形状重叠 我正在通过异步任务下载图像
  • ios音频单元remoteIO录音时播放

    我被要求将 VOIP 添加到游戏中 跨平台 因此无法使用 Apple gamekit 来做到这一点 已经有三四天了 我一直在努力让我的注意力集中在音频单元和远程IO上 我忽略了数十个示例等 但每次都只是对输入 PCM 应用简单的算法并在扬声
  • 使用 NSXMLParser 解析 XML

    我有一个关于 xml 解析的问题 通常 XML文件的样式是这样的
  • 如何在spark scala中使用带有2列的array_contains?

    我有一个问题 我想检查字符串数组是否包含另一列中存在的字符串 我目前正在使用下面的代码 该代码给出了错误 withColumn is designer present when array contains col list of desi
  • R 中的双冒号 (::) 是什么?

    我正在关注 Rbloggers 中的教程 发现双冒号的使用 我在网上查找 但找不到其使用的解释 这是它们的使用示例 df lt dplyr data frame year c 2015 NA NA NA trt c A NA B NA 我知
  • Greasemonkey @require 在 Chrome 中不起作用

    我正在尝试使用 Greasemonkey 添加 jQuery require include方法 但是不起作用 显示以下错误 Uncaught ReferenceError is not defined repeated 10 times
  • WinForm c#:检查首次运行并显示消息

    我正在创建一个包含首次运行检查的 winform 应用程序 我一直在关注这两篇文章 如何检查程序是否是第一次运行 C 中的 Windows 窗体用户设置 首次运行检查应该检查应用程序是否曾经运行过 如果没有运行过 它应该向用户显示一些消息
  • 在 TypeScript 中扩展特定类型的数组

    我知道如何扩展任何类型的数组 declare global interface Array
  • MongoDB NodeJS 本机驱动程序(mongodb) 与 Mongo Shell 性能对比

    我在 MongoDB 表 1 中有 10000 条记录 数据如下 id ObjectId 5d5e500cb89312272cfe51fc cities cityid 5d5d2205cdd42d1cf0a92b33 value XYZ c
  • Android 活动识别不适用于 Nexus 5

    我有一个正在使用谷歌活动识别更新的代码 现在突然之间 这些似乎每秒发送几次更新 或者从不发送更新 尽管每 20 秒请求一次 我没有更改代码并检查了早期版本 但遇到了同样的问题 我根据教程构建了一个最小的示例 但我的 Nexus 5 设备没有
  • 量词与非量词

    我有一个关于量词的问题 假设我有一个数组 我想计算该数组的数组索引 0 1 和 2 declare const cpuA Array Int Int assert or select cpuA 0 0 select cpuA 0 1 ass
  • C 宏将字符串转换为 pascal 字符串类型

    我想要一些关于宏的想法 用于将预处理器定义的字符串转换为 pascal 类型字符串 然后能够使用宏来初始化 const char 数组等 像这样的事情会很棒 define P STRING CONV str const char strin
  • 以编程方式锁定或关闭屏幕

    我想要turn off 锁定屏幕以编程方式控制我的设备 目前 当我尝试时 DevicePolicyManager mDPM DevicePolicyManager getSystemService Context DEVICE POLICY
  • 在 C# 中自动完成文本框

    我正在尝试自动完成文本框 我正在从 Access 数据库检索值 仅数据表中的一个字段 如果有人可以帮助我 AutoCompleteStringCollection autoCompleteList new AutoCompleteStrin
  • 如何在android中改变位图图像的颜色?

    我正在开发一个 Android 应用程序 其中我将图像设置为 imageview 现在 我想以编程方式更改位图图像颜色 假设我的图像最初是红色的 现在我需要将其更改为橙色 我怎样才能做到这一点 请帮忙 这是我的代码 我设法改变不透明度 但我
  • Rails 路由和控制器模块 - 命名空间?

    我无法为我的控制器创建模块 也无法让我的路由指向控制器内的该模块 出现此错误 Routing Error uninitialized constant Api Fb 所以 这就是我的路线设置方式 namespace api do names
  • ConnectionAbortedError: [WinError 10053] 已建立的连接被主机中的软件中止

    由于某种原因 我收到以下错误only当我打开一个嵌套的webdriver实例 不知道这里发生了什么 我在用Windows 10 壁虎驱动程序 0 21 0 and Python 3 7 连接中止错误 WinError 10053 An es
  • Xcode 可以在 M1 Mac 上构建本机 Intel 二进制文件吗

    是否可以在 M1 Mac 上使用 Xcode 构建本机 Intel 二进制文件 我想开始使用 M1 架构进行测试 但仍需要继续构建原生英特尔应用程序 而无需进行任何更改 M1 Mac 上的 Xcode 将构建一个通用二进制文件 其中包含两者
  • anaconda 找不到我已经安装的包

    我正在尝试通过克隆安装 doconce https github com hplgit doconce using sudo python setup py install 这样就安装成功了并且which doconce回报 gt usr
  • Android volley中处理多个请求

    我正在尝试使用 Volley 处理多个请求 并且我收到了所有请求的响应 我的问题是如何识别响应属于哪个API mQueue CustomVolleyRequest getInstance this getApplicationContext