我当前在一个项目上使用排球,我想发送一个 JSON正文并检索一个字符串作为响应。
为此,我创建了一个以JsonRequest作为父类的类。
它看起来像这样:
public class JAStringRequest extends JsonRequest<String> {
private String token;
private Response.Listener<String> listener;
@Nullable
private Response.ErrorListener errorListener;
public JAStringRequest(String token, int method, String url, @Nullable String requestBody, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
this.token = token;
this.listener = listener;
this.errorListener = errorListener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
try {
HashMap<String, String> headers = new HashMap<>();
String auth = "Bearer " + token;
headers.put("Authorization", auth);
headers.put("Content-Type", "application/json");
return headers;
} catch (Exception e) {
Log.e(TAG, "Authentication Failure");
}
return super.getHeaders();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d(TAG, "parseNetworkResponse " + response.statusCode);
try {
String jsonString =
new String(
response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(
jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(String response) {
super.deliverResponse(response);
Log.d(TAG, "deliverResponse: " + response);
listener.onResponse(response);
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.d(TAG, "parseNetworkError");
if (volleyError.networkResponse != null
&& volleyError.networkResponse.data != null) {
volleyError = new VolleyError(new String(
volleyError.networkResponse.data));
return volleyError;
}
return null;
}
}
问题在于,我从未从 parseNetworkResponse 中检索到响应。 (日志“ parseNetworkResponse 200”)
JAStringRequest request = new JAStringRequest(jwtToken, Request.Method.POST, url.toString(), array.toString(),
response -> {
if (response.equals("200")) {
Log.d(TAG, "DBrequest result: " + key + " => " + response);
} else {
Log.d(TAG, "DBrequest error: " + key + " => " + response);
}
isRequestEnded.set(true);
},
error -> {
Log.d(TAG, "DBrequest Error message: " + key + " => " + error.getMessage());
});
request.setTag(key);
queue.add(request);
这里永远不会触发监听器,也不显示日志。
有任何线索吗?
谢谢!
答案 0 :(得分:0)
我通过在自定义JsonRequest类中添加布尔值来使其工作。将此布尔值初始化为false,然后在parseNetworkResponse中将其传递为true。 当这个布尔值为true时,我们就不使用了。
public class JAStringRequest extends JsonRequest<String> {
...
private boolean isResponse = false;
...
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d(TAG, "parseNetworkResponse");
isResponse = true;
...
}
...
public boolean isResponse() {
return isResponse;
}
}
queue.add(request);
while (!request.isResponse()) {
}
这是我发现使其工作的唯一方法,否则响应永远不会传递到response.listener。
PS:在for循环中,有一段时间像LIFO一样执行请求。