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

Alamofire请求ISBNdb多ISBN无结果问题求助

问题分析与解决

问题背景

尝试通过ISBNdb API批量获取两个ISBN的JSON数据,Curl请求可正常返回结果,但使用Alamofire的AF.request时,单个ISBN请求正常,用逗号、&、%20、+等多种方式分隔多个ISBN均无返回结果。

原请求代码

Curl请求:

/* curl from ISBNdb
curl -X 'POST' \
  'https://api2.isbndb.com/books' \
  -H 'accept: application/json' \
  -H 'Authorization: mykey' \
  -H 'Content-Type: application/json' \
  -d 'isbns=9781250178633,9781501110368'
*/

Alamofire代码:

func fetchAPIDataISBN() {
    let headers: HTTPHeaders =  ["accept": "application/json","Authorization": "mykey","Content-Type": "application/json"]
    //let parameters1 = ["isbns": "9781250178633,9781501110368"]
    let parameters = ["isbns": "9781250178633"]
    AF.request("https://api2.isbndb.com/books", method: .post, parameters: parameters, headers: headers)
}

核心原因

参数编码方式不匹配:

  • 你的Curl请求虽然声明Content-Type: application/json,但实际通过-d传递的是**x-www-form-urlencoded格式**的键值对(isbns=ISBN1,ISBN2),接口实际按该格式解析参数。
  • Alamofire默认会将字典参数编码为JSON格式(请求体为{"isbns": "ISBN1,ISBN2"}),与接口期望的格式不符,导致批量请求失败;单个ISBN请求正常大概率是接口兼容了两种格式。

解决方案

修改Alamofire请求,指定使用URLEncoding(表单编码),并修正请求头的Content-Type以匹配实际传参格式:

func fetchAPIDataISBN() {
    let headers: HTTPHeaders = [
        "accept": "application/json",
        "Authorization": "mykey",
        "Content-Type": "application/x-www-form-urlencoded"
    ]
    // 使用逗号分隔多个ISBN,保持和Curl一致的参数格式
    let parameters = ["isbns": "9781250178633,9781501110368"]
    
    AF.request("https://api2.isbndb.com/books",
               method: .post,
               parameters: parameters,
               encoding: URLEncoding.httpBody, // 指定表单编码方式
               headers: headers)
        .responseJSON { response in
            switch response.result {
            case .success(let data):
                print("批量获取成功: \(data)")
            case .failure(let error):
                print("请求失败: \(error.localizedDescription)")
            }
        }
}

补充说明

如果接口确实支持JSON格式传参,也可以直接构造JSON请求体,但需要确认接口接收的JSON结构(比如是否需要将ISBN放在数组中)。但根据你的Curl请求表现,表单编码是更可靠的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:54:49