gzip压缩API呼叫swift

发布于 2025-01-25 22:42:54 字数 289 浏览 5 评论 0原文

我正在使用Swift工作的API工作,该API需要您在HTTP请求的主体中使用GZIP或Deflate发送JSON。如何将下面的testEventModel转换为所需的压缩JSON格式?

struct EventModel: Codable {
    var eventType: String
    var eventName: String?
}

var testEventModel = EventModel(eventType: "TestEvent", eventName: "TestName")

I'm working in Swift with an API that requires you to send JSON compressed using gzip or deflate in the body of your HTTP request. How would I convert testEventModel below into the required compressed JSON format?

struct EventModel: Codable {
    var eventType: String
    var eventName: String?
}

var testEventModel = EventModel(eventType: "TestEvent", eventName: "TestName")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千笙结 2025-02-01 22:42:54

最简单的方法是将现有库用于gzzipping内容,例如: https://github.com/ 1024JP/gzipswift 。然后,您的代码看起来如下:

guard let jsonData = try? JSONEncoder().encode(testEventModel),
      let url = URL(string: "https://api.com/endpoint") else {
    return
}
let gzipped = jsonData.gzipped()

var request = URLRequest(url: url)
let postLength = String(format: "%lu", UInt(gzipped.count))
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.addValue("gzip", forHTTPHeaderField: "Content-Encoding")
request.httpBody = gzipped

URLSession.shared.dataTask(with: request) { data, response, error in
    // handle response
}.resume()

Simplest way, would be to use an existing library for gzipping content, like this one: https://github.com/1024jp/GzipSwift . then your code could look like follows:

guard let jsonData = try? JSONEncoder().encode(testEventModel),
      let url = URL(string: "https://api.com/endpoint") else {
    return
}
let gzipped = jsonData.gzipped()

var request = URLRequest(url: url)
let postLength = String(format: "%lu", UInt(gzipped.count))
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.addValue("gzip", forHTTPHeaderField: "Content-Encoding")
request.httpBody = gzipped

URLSession.shared.dataTask(with: request) { data, response, error in
    // handle response
}.resume()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文