带有JSON主体的StringRequest

Car*_*s J 5 android json android-volley

我正在尝试使用Volley发送请求,但我无法确定如何使其工作.

我需要发送一个带有JSON编码数据的POST请求作为正文,但经过几个小时尝试不同的东西后,我仍然无法使其工作.

这是我当前的请求代码:

User user = User.getUser(context);
String account = user.getUserAccount();
String degreeCode = user.getDegreeCode();

final JSONObject body = new JSONObject();
try {
    body.put(NEWS_KEY, 0);
    body.put(NEWS_DEGREE, degreeCode);
    body.put(NEWS_COORDINATION, 0);
    body.put(NEWS_DIVISION, 0);
    body.put(NEWS_ACCOUNT, account);
} catch (JSONException e) {
    e.printStackTrace();
}

StringRequest request = new StringRequest(Request.Method.POST, GET_NEWS, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(String response) {
        Log.i(TAG, response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Error: " + getMessage(error, context));
        Toast.makeText(context, getMessage(error, context), Toast.LENGTH_SHORT).show();
    }
}) {
    @Override
    public byte[] getBody() throws AuthFailureError {
        return body.toString().getBytes();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        return headers;
    }
};
queue.add(request);
Run Code Online (Sandbox Code Playgroud)

但是这段代码总是返回"Bad request error"

我试过的一些事情:

  • 覆盖getParams()方法而不是getBody().(没用)
  • JSONObjectRequest在构造函数上发送一个body.这个工作,但因为我的Web服务返回一个String值,我总是得到一个ParseError.这就是我使用的原因StringRequest.

很感谢任何形式的帮助.

And*_* T. 14

正如在njzk2的评论中已经提到,最简单的方法是改写getBodyContentType().覆盖getHeaders()也可能有效,但是你需要放置所有必需的头文件Content-Type,因为你基本上覆盖了原始方法设置的头文件.

您的代码应如下所示:

StringRequest request = new StringRequest(...) {
    @Override
    public byte[] getBody() throws AuthFailureError {
        return body.toString().getBytes();
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }
};
Run Code Online (Sandbox Code Playgroud)