如何在swift中使用Alamofire设置发布参数

问题描述:

我正在使用Alamofire在发送http请求/发布到服务器。以下是我在swift中使用的代码。如何在swift中使用Alamofire设置发布参数

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. 

我觉得问题会由没有正确设置参数的swift代码引起。但我不知道如何正确设置它们?

你的swift代码看起来不错。确保问题发生在哪个方面。您可以试试https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en来测试api,并确保api没有任何问题。

您也可以尝试将friend_id和skill_id的数据类型更改为服务器端的字符串,然后再次运行。

我找到了一些搜索后的解决方案。我需要在下面的请求方法中添加“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) 
     })