像这样,我想将 JSON 正文请求发送到 GET API。
尝试过,但没有成功:
public static void getQuestionsListApi2(final String requestId, final String timestamp,
final ImageProcessingCallback.downloadQuestionsCallbacks callback,
final Context context) {
try {
String url = NetUrls.downloadQuestions;
final JSONObject jsonBody = new JSONObject();
jsonBody.put("requestId", requestId);
jsonBody.put("timestamp", timestamp);
final String mRequestBody = jsonBody.toString();
Log.i("params", String.valueOf(jsonBody));
Log.i("URL", url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, **jsonBody**, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Log.v("TAG", "Success " + jsonObject);
callback.downloadQuestionsCallbacksSuccess(jsonObject.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.v("TAG", "ERROR " + volleyError.toString());
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
}
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
这是我发送时使用的代码
JSONRequest
。使用 GET 方法,我从服务器收到 400 错误响应 并且服务器不接受 URL 表单中的数据。我正在发送 jsonBody
对象作为参数。有什么解决办法吗?
如果你想在GET请求的body中传递Json数据,你必须使用Query注解
Call<YourNodelClass> getSomeDetails(@Query("threaded") String threaded, @Query("limit") int limit);
这将作为 Json 对象传递
{"threaded": "val", "limit": 3}
。
我已经尝试过,这只是工作代码。
您可以使用改造来发送带有正文的请求。 http://square.github.io/retrofit/
使用库很简单,例如:
@GET("[url node]")
Single<Response<ResponseBody>> doSmt(@Header("Authorization") String token, @Body ListRequest name);
此外,请查看此处有关带有 body 的 get 方法 带有请求正文的 HTTP GET
带有请求正文的 GET 方法是可选的此处。然而,这个 RFC7231 文档说,
在 GET 请求上发送有效负载正文可能会导致一些现有的 拒绝请求的实现。
这意味着不建议这样做。使用POST方法来使用请求体。
从维基百科查看此表。