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

使用Alamofire发起POST请求时持续报-1005错误,Postman正常

解决Alamofire POST请求出现NSURLErrorDomain Code=-1005的问题

针对你遇到的"网络连接丢失"错误,且Postman请求正常的情况,可按以下步骤排查解决:

1. 修复URL处理逻辑

你代码中对URL的额外编码处理可能破坏了原URL结构:

// 原错误代码
guard let url = urlComponents.url?.absoluteString.removingPercentEncoding else { return .failure(.invalidURL) }
var urlRequest = try URLRequest(url: url.asURL())

removingPercentEncoding会还原URL中的编码字符,可能导致URL包含非法字符,重新转URL时引发底层连接问题。直接使用URLComponents生成的URL即可:

// 修改后
guard let url = urlComponents.url else { return .failure(.invalidURL) }
var urlRequest = URLRequest(url: url)

2. 确认请求头的Content-Type设置

Postman会自动为JSON请求添加Content-Type: application/json,但Alamofire不会默认添加。如果你的请求body是JSON格式,需确保endpoint.header中包含该字段:

// 示例:在构造endpoint时添加
let headers: HTTPHeaders = [
    "Content-Type": "application/json",
    // 其他请求头
]

如果是form-data或x-www-form-urlencoded格式,需对应设置正确的Content-Type。

3. 调整Alamofire Session的连接配置

服务器可能对HTTP版本、连接复用有特定要求,可尝试修改Session配置:

// 创建自定义Session
let configuration = URLSessionConfiguration.default
configuration.httpMaximumConnectionsPerHost = 1
configuration.httpShouldUsePipelining = false
configuration.httpVersion = .http1_1 // 强制使用HTTP/1.1,避免HTTP/2兼容性问题
let session = Session(configuration: configuration)

// 使用该Session发起请求
let request = session.request(urlRequest).serializingDecodable(responseModel)

4. 验证请求Body的编码正确性

对比Postman的请求Body和你代码中生成的Body,确保内容和编码完全一致:

  • 如果是JSON Body,建议用JSONEncoder序列化,避免手动拼接出错:
    let encoder = JSONEncoder()
    if let body = try? encoder.encode(yourRequestBodyModel) {
        urlRequest.httpBody = body
    }
    
  • 打印Body的字符串版本,和Postman中的Raw Body对比:
    print("Request Body: \(String(data: urlRequest.httpBody ?? Data(), encoding: .utf8) ?? "")")
    

5. 检查ATS证书兼容性

即使开启了NSAllowsArbitraryLoads,部分服务器的SSL证书配置仍可能导致iOS连接失败。可临时添加更宽松的ATS配置到Info.plist排查:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>你的目标域名</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
        </dict>
    </dict>
</dict>

注意:正式发布时需根据服务器证书配置调整为合规的ATS设置,不要保留过度宽松的配置。


内容的提问来源于stack exchange,提问作者Andrės Fonseca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:35:36