2016-03-21 33 views
0

我正在使用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代碼引起。但我不知道如何正確設置它們?

回答

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) 
     }) 
相關問題