嗨,我是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)")
}
框架的代码
@RequestMapping(value="user", method=RequestMethod.POST)
public JSONObject addUser(
@RequestBody Memberinfo member,
HttpServletRequest request) {
JSONObject result = new JSONObject();
return result;
}
-在控制器中用于检索@RequestBody的-Memberinfo.java
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";
})
最佳答案
我认为参数应该发送如下
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之类的东西测试您的终结点
关于swift - 向Spring服务器发出发布请求时出现400错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56512317/