【问题标题】:Volley GET JsonObjectRequest with JSONObjectParameter doesn't work at all带有 JSONObjectParameter 的 Volley GET JsonObjectRequest 根本不起作用
【发布时间】:2023-03-27 08:50:01
【问题描述】:

我遇到了 Volley 请求的问题 - 我想使用 JSONObject 参数(用户有密码和登录名)发送 GET(也是另一个类似的 POST)请求来授权用户并发回完整的用户数据。虽然在调试过程中我可以看到 mRequestBody 是正确的 JSON 但我的控制器无法接收它 -

private void processLogin() throws JSONException {
    this.user.setLogin(this.loginText.getText().toString());
    this.user.setPassword(this.passwordText.getText().toString());
    final JSONObject jsonObject = new JSONObject(new Gson().toJson(this.user));

    final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, UrlHelper.loginUrl, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            user = new Gson().fromJson(response.toString(), User.class);
            if (user.getUserId().equals(getResources().getString(R.string.ERROR))) {
                onLoginFailed();
            } else {
                onLoginSuccess(user);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, error.toString());
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };
    VolleySingleton.getInstance(this).addToRequestQueue(request);
}

控制器方法:

@RequestMapping(value = "/loginTest", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public User someMethod(@RequestBody User user) throws SQLException {
    return userService.authenticateUser(user.getLogin(), user.getPassword());
}

没有注释@RequestBody我处理但param中的用户为空,所以我处理用户密码为空并登录。最近我通过StringRequest 做到了,请帮帮我。 :)

【问题讨论】:

    标签: java android json controller android-volley


    【解决方案1】:

    作为 HTTP 规范的一部分,GET 请求没有正文。您可以创建和发送带有主体的 GET 请求,但这没有意义,因为主体在 GET 方法规范中没有语义意义。我对 Spring 不太了解,但我的猜测是 Spring 可能会忽略请求的主体,因为它是一个 GET 方法。如果您打算在正文中放入某些内容,则应该以 POST 的形式发送和接收请求。

    【讨论】:

    • 好吧,所以我将我的方法更改为 POST,使用 StringRequest 并为其实现 getBodyContentType() 和 getBody() 方法,并改进我的控制器方法。感谢您的帮助:)
    猜你喜欢
    • 2021-06-21
    • 1970-01-01
    • 2017-06-09
    • 2013-11-19
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多