swift - 如何使用 Alamofire 框架调用带有请求正文的 http POST 端点

标签 swift http-post alamofire

我正在开发一个iOS应用程序,并且我是iOS开发的新手。 为了处理 http 请求和响应,我选择了 Alamofire 框架。

现在我必须用 body 发出一个 http post 请求。 让我再描述一下:

我的 API 如下所示:

@RequestMapping(path = "/block/arena/v1", method = RequestMethod.POST)
    public Response blockArena (@RequestBody(required = true)  testRequest request) 
    {
        Response response = arenaBlockServiceImpl.block(request);
        return respose;
    }

Class testRequest {
    List<Object> ObjectList1;
    List<Object> ObjectList2;
    private int ObjectList1Count = 0;
    private int ObjectList2Count = 0;

    // and its getters and setters
}

========

现在我如何在 iOS swift 代码(或使用 Alamofire)中调用我的 API?任何可能的方法都值得赞赏。谢谢

最佳答案

构建标题:

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

将参数构建为 [String: Any] 字典:

let parameters: [String, Any] = [
            "name": name as String,
            "id": id as Int,
           ]

然后构建您的网址:

let yourAPI = ""http://yourEndPoint"
let yourEndPoint = "\(yourAPI)//block/arena/v1"

最后调用 Alamofire 电话:

Alamofire.request(yourEndPoint, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseData { response in
// process response with codable, or SwiftyJson pod
}

使用Alamofire,您还可以执行resposceJSON 而不是responseData。我使用数据是因为我使用 swiftyJson 处理响应并发现 responseData 效果很好

关于swift - 如何使用 Alamofire 框架调用带有请求正文的 http POST 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48932905/

相关文章:

swift - reloadRows 无法正常工作

ios - 在 Swift 中,如何在不同的 ViewController 中永久更改 a 的标签文本?

ios - GMSMutablePath 删除/替换坐标问题,折线

php - Android - 将 JSONArray 发送到 php

PHP 表单大小截断

ios - XCode 7.3 和 Swift 2.2 中没有这样的模块 'Alamofire'

ios - Alamofire NSURLRequest 不明确使用 URLString

swift - 切换文本字段类

php - 如何正确使用 AngularJS $http.post 通过 PHP 更新 MySQLi 表?

ios - 如何通过 Alamofire 和 SwiftyJSON 在 UIViewController 中使用根目录中的 JSON 对象