You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Pastebin API在Swift 4请求中异常:提示需用POST而非GET

解决Pastebin API的"Bad API request, use POST request, not GET"错误

我之前也碰到过类似的API请求问题,咱们来一步步排查你的代码问题!你的cURL请求正常但Swift代码失败,核心问题几乎肯定是缺少了POST表单请求必需的Content-Type请求头。Pastebin的API服务器需要明确知道你发送的是表单数据,否则可能会错误地将你的请求识别为GET请求,或者无法解析POST体内容。

问题分析

你的代码里已经设置了httpMethod = "POST",也传入了POST体,但没有告诉服务器这个POST体是application/x-www-form-urlencoded格式的表单数据。很多服务器(包括Pastebin的)会因为缺少这个头而无法正确处理请求,进而返回"使用POST而非GET"的错误提示。

修复步骤

  1. 添加Content-Type请求头
    在设置httpBody之前,给request添加如下头信息——这是让服务器正确识别表单POST请求的关键:

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    
  2. 确保内容正确编码
    虽然你提到已经做了urlEscapedContent,但建议确认编码方式是否正确,推荐使用系统自带的编码方法,避免手动编码遗漏特殊字符:

    guard let urlEscapedContent = originalContent.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
        // 处理编码失败的情况
        callback("内容编码失败")
        return
    }
    

修改后的完整代码

func postPasteRequest(urlEscapedContent: String, callback: @escaping (String) -> ()) { 
    guard let apiUrl = URL(string: "http://pastebin.com/api/api_post.php") else {
        callback("无效的API地址")
        return
    }
    var request = URLRequest(url: apiUrl) 
    request.httpMethod = "POST"
    // 添加关键的Content-Type头,让服务器识别表单数据
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    
    let postString = "api_paste_code=\(urlEscapedContent)&api_dev_key=\(API_KEY)&api_option=paste&api_paste_private=1&api_paste_expire_date=N" 
    request.httpBody = postString.data(using: .utf8) 
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
        guard let data = data, error == nil else {
            NSLog("error=\(String(describing: error))") 
            callback("网络请求错误: \(error?.localizedDescription ?? "未知错误")")
            return 
        } 
        
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { 
            NSLog("statusCode should be 200, but is \(httpStatus.statusCode)") 
            NSLog("response = \(String(describing: response))")
            callback("请求失败,状态码: \(httpStatus.statusCode)")
            return
        } 
        
        if let responseString = String(data: data, encoding: .utf8) {
            callback(responseString)
        } else {
            callback("无法解析响应内容")
        }
    } 
    task.resume() 
}

额外检查点

  • 确认你的API_KEY是正确且有效的,没有拼写错误
  • 确保api_option=paste参数没有写错,这个参数是告诉API执行粘贴操作的核心标识
  • 如果还是有问题,可以打印出完整的request信息(比如request.allHTTPHeaderFieldsrequest.httpBody),对比cURL的请求头和体,看哪里存在差异

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

火山引擎 最新活动