You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中URLSession POST请求无法接收完整服务端响应问题

Swift URLSession请求400状态码相关问题及解决记录

问题代码

func load<T: Codable>(_ resource : Resource<T>) async throws -> T {
    var request = URLRequest(url:resource.url)
    switch resource.method {
        case .get(let queryItems):
            var components = URLComponents(url: resource.url, resolvingAgainstBaseURL: false)
            if !queryItems.isEmpty {
                components?.queryItems = queryItems
            } 
            guard let url = components?.url else {
                throw NetworkError.badRequest
            }
            request = URLRequest(url:url)
    case .post(let data):
        request.httpMethod = resource.method.name
        request.httpBody = data
    case .delete:
        request.httpMethod = resource.method.name
    }
    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = ["Content-Type": "application/json"]
    let session = URLSession(configuration: configuration)
    let (data, response) = try await session.data(for: request)
    guard let httpResponse = response as? HTTPURLResponse else {
            throw NetworkError.invalidResponse
    }
    print("Here is httpResponse")
    print(httpResponse)
    print(httpResponse.statusCode)
    guard let result = try? JSONDecoder().decode(resource.modelType, from: data) else {
        print("print error")
        print("\(data.debugDescription)")
        throw NetworkError.decodingError
    }
    print(result)
    return result
}

问题现象

在SwiftUI应用中使用上述代码发起HTTP(S)请求时,出现以下异常:

  • 执行特定配置/负载时,仅能输出400状态码及响应头,无法获取curl请求中能看到的错误JSON内容
  • 服务端返回400状态码时,代码无法解码响应数据并抛出异常,但对应的Swift结构体格式与错误JSON匹配
  • 注:200状态码的响应可正常捕获和解码

疑问

  • 为何Swift输出中看不到curl返回的错误JSON?
  • 为何400状态下解码失败?
  • 如何捕获该错误JSON并解码为Swift结构体?

问题解决(2023年6月19日)

原因是服务端返回的JSON格式错误,感谢CouchDeveloper协助排查。

内容的提问来源于stack exchange,提问作者itpragmatik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:12:42