gpt4 book ai didi

android - 如何为请求设置标签并从 Response Volley 异步请求中获取?

转载 作者:行者123 更新时间:2023-11-29 20:02:05 25 4
gpt4 key购买 nike

我有一个包含多个 REST Api 的 Android 应用程序。 API 使用 Volley 库进行管理。响应越来越好,而且一切正常。但是当我进行异步请求时,我无法识别每个请求的响应。

我的请求方式是这样的:

private void httpCall(String URL, String json, String session key, int type) {
try {
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null,
null,
null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);

Log.i(REQUEST_TAG, "httpCall=url" + url + "::type" + type);
Log.i(REQUEST_TAG, "httpCall=json" + json);
} catch (Exception e) {
e.printStackTrace();

}
if (mContext != null)
mQueue = CustomVolleyRequestQueue.getInstance(mContext).getRequestQueue();
else
mQueue = CustomVolleyRequestQueue.getInstance(mActivity).getRequestQueue();
JSONObject mJSONObject;
final CustomJSONObjectRequest jsonRequest;
try {
if ((json != null) && (json.trim().length() > 0)) {
mJSONObject = new JSONObject(json);
} else {
mJSONObject = new JSONObject();
}
jsonRequest = new CustomJSONObjectRequest(sessionkey, type, url, mJSONObject, this, this);
// Wait 20 seconds and don't retry more than once
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}

是否有任何选项可以为请求设置标签并从响应中获取相同的标签?这样我就可以识别当前的请求和响应。我不知道这是一个重复的问题,但我没有得到正确的解释。

我的回复方式是:

@Override
public void onResponse(Object response) {
if (response != null) {

// I want to trigger the request tag from here

mCallBack.onSuccessData(response);
}
}

请求和响应方法在同一个类中,该类实现了 Response.Listener、Response.ErrorListener。

最佳答案

您分配给请求的标签存储在变量 mTag 中,该变量在请求的整个生命周期中持续存在。

public Request<?> setTag(Object tag) {
mTag = tag;
return this;
}

对于我的应用程序,我稍微修改了以下 Volley 类:

在类请求中将 mTag 的可见性从私有(private)更改为 protected

/** An opaque token tagging this request; used for bulk cancellation. */
protected Object mTag;

在类Response中,在Listener接口(interface)定义的回调函数onResponse中添加Object标签

/** Callback interface for delivering parsed responses. */
public interface Listener<T> {
/** Called when a response is received. */
public void onResponse(Object tag, T response);
}

在实现接口(interface) Response.Listener 的类中,例如 JsonRequest

@Override
protected void deliverResponse(T response) {
mListener.onResponse(mTag, response);
}

关于android - 如何为请求设置标签并从 Response Volley 异步请求中获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36127870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com