gpt4 book ai didi

ios - URlRequest.httpBody 在 startLoading() 方法中是 nil swift 3.0 中的 URLProtocol

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:26:13 27 4
gpt4 key购买 nike

我有我的自定义 URLProtocol,它有一些自定义响应生成。现在我有一个要求,我需要在获得实际响应之前通过 httpBody 向服务器发送一些信息(可以是 json/String 作为数据)

我的问题是,当我使用 httpBody 创建 urlRequest 时,然后通过使用 URLSession 和一些 session 配置(那个自定义 URLProtocol 包含在这里)

这将首先调用 canInit -> canonical -> startLoading -> stopLoading,在这些所有方法中,request.httpBody 为 nil。

override func startLoading() {
let request = self.request
var response: HTTPURLResponse?
let hasResponse: Bool = true
if request.httpMethod == "GET" || request.httpMethod == "POST" {
guard let url = request.url else {
return
}
let client = self.client
let statusCode = 200
if url.absoluteString.contains("/good") {
print(self.request.httpBody) //here its nil
}
response = hasResponse ? HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: cannedHeaders) : nil
client?.urlProtocol(self, didLoad: responseData)
client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: URLCache.StoragePolicy.notAllowed)
client?.urlProtocolDidFinishLoading(self)
}
}
func testCompressRequest() {
let expect = expectation(description: "testCompressRequest")
let urlRequest = URLRequest(url: URL(string:serverPath+"/good")!)
urlRequest.httpBody = "someMethodBodyasString".data(using: .utf8)
urlRequest.httpMethod = "POST"
urlRequest.allHTTPHeaderFields = ["Accept-Encoding": "gzip, deflate", "Content-Encoding":"gzip, deflate", "Content-Type":"application/json", "Accept":"application/json", "Content-Length":String(describing: urlRequest.httpBody?.count)]
let task = URLSession(configuration: sessionConfig).dataTask(with: urlRequest) { (data, response, error) in
expect.fulfill()
}
task.resume()
waitForExpectations(timeout: 10, handler: nil)
}

最佳答案

当协议(protocol)看到请求对象时,正文数据对象已经被标准化为正文流对象。打开正文流并从那里读取数据。

关于ios - URlRequest.httpBody 在 startLoading() 方法中是 nil swift 3.0 中的 URLProtocol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com