向Spring服务器发出发布请求时出现400错误

时间:2019-06-09 05:54:08

标签: swift spring alamofire

嗨,我是Swift的新手,正在尝试制作一个简单的应用程序。

我正在使用“ alamofire 5 beta 6”发出请求。

下面是一些代码

-发出发布请求的代码

 var json:JSON = JSON(["id":id.text, "password":enteredPassword])

    var parameters: Parameters = ["id":id.text, "password":enteredPassword]


    let headers:HTTPHeaders = [ "Content-Type":"application/json"]

    AF.request("http://127.0.0.1:8080/user", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON{
        response in


        print("response : \(response)")
    }

-Spring框架代码

    @RequestMapping(value="user", method=RequestMethod.POST)
    public JSONObject addUser(
            @RequestBody Memberinfo member,
            HttpServletRequest request) {


        JSONObject result = new JSONObject();

        return result;
    }

-Memberinfo.java,在控制器中用于检索@RequestBody

public class Memberinfo {

String id;
String password;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
}

在Swift代码中,我设置了参数ID和密码以在Spring框架中将其取回。

但是,在我发出请求后,Alamofire便显示了消息

response : success({
error = "Bad Request";
message = "JSON parse error: Unrecognized token 'id': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'id': was expecting ('true', 'false' or 'null')\n at [Source: (PushbackInputStream); line: 1, column: 4]";
path = "/user";
status = 400;
timestamp = "2019-06-09T05:46:07.417+0000";
})

1 个答案:

答案 0 :(得分:0)

我认为应按以下方式发送参数

var parameters: Parameters = {"id":id.text, "password":enteredPassword}

另一个重要的事情,您不需要将JSONObject作为端点的响应类型,您只需使用@ReponseBody注释端点即可获得JSON响应

@RequestMapping(value="user", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<JSONObject> addUser(
        @RequestBody Memberinfo member,
        HttpServletRequest request) {


    JSONObject result = new JSONObject();

    return result;
}

在从外部源调用此终结点之前,始终使用Postman或RestClient之类的东西来测试终结点