我正在开发一个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/