我在swift中使用Alamofire向服务器发送http请求/帖子。下面是我在swift中使用的代码。
Alamofire.request(.POST, "http://localhost:8080/hello", headers: [ACCESS_TOKEN:token, "Content-Type":"application/x-www-form-urlencoded" ],
parameters:["friend_id" : friendId, "skill_id" : skillId]).response(completionHandler: {
(request, response, data, error) in
print(request)
print(response)
print(data)
print(error)
})
以下是服务器端定义的代码:
@POST
@Path("/hello")
@Produces(MediaType.APPLICATION_JSON)
public Response nominateSkill(@Context HttpServletRequest request, @FormParam("friend_id") long friendId, @FormParam("skill_id") int skillId) {
// ...
}
当我运行swift代码时,我总是在服务器端收到以下错误消息:
A servlet request to the URI http://localhost:8080/hello contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using @FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
我认为问题会受到没有正确设置参数的快速代码的影响。但我不知道如何正确设置它们?
答案 0 :(得分:1)
我在搜索后找到了解决方案。我需要在请求方法上添加“encoding:.URL”,如下所示:
Alamofire.request(.POST, "http://localhost:8080/hello", headers: [ACCESS_TOKEN:token, "Content-Type":"application/x-www-form-urlencoded" ],
parameters:["friend_id" : friendId, "skill_id" : skillId],
encoding: .URL).response(completionHandler: {
(request, response, data, error) in
print(request)
print(response)
print(data)
print(error)
})
答案 1 :(得分:0)
你的快捷代码似乎很好。确保出现问题的哪一方面。您可以尝试https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en来测试API,并确保api没有任何问题。
您也可以尝试将friend_id和skill_id的数据类型更改为服务器端的字符串并再次运行。