【问题标题】:POST request with a simple string in body with Alamofire使用 Alamofire 在正文中使用简单字符串的 POST 请求
【发布时间】:2026-01-22 00:20:05
【问题描述】:

如何在我的 iOS 应用程序中使用 Alamofire 在 HTTP 正文中发送带有简单字符串的 POST 请求?

默认 Alamofire 需要请求参数:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])

这些参数包含键值对。但我不想在 HTTP 正文中发送带有键值字符串的请求。

我的意思是这样的:

Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString")

【问题讨论】:

    标签: ios http swift request alamofire


    【解决方案1】:

    您的示例Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) 已经包含“foo=bar”字符串作为其主体。 但是如果你真的想要自定义格式的字符串。你可以这样做:

    Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({
                (convertible, params) in
                var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
                mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                return (mutableRequest, nil)
            }))
    

    注意:parameters 不应为 nil

    更新(Alamofire 4.0、Swift 3.0):

    在 Alamofire 4.0 API 已更改。因此,对于自定义编码,我们需要符合ParameterEncoding 协议的值/对象。

    extension String: ParameterEncoding {
    
        public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var request = try urlRequest.asURLRequest()
            request.httpBody = data(using: .utf8, allowLossyConversion: false)
            return request
        }
    
    }
    
    Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
    

    【讨论】:

    • 这非常有效,不仅适用于简单的,而且适用于各种 JSON 类型的映射字符串。
    • @silmaril 在我的情况下,只有使用 PUT 方法才能从后端获取原始请求,请您帮帮我,为什么 POST 请求什么都看不到
    • .Custom 在 Alamofire 4 Swift 3 中不再可用,我找不到替代方案,有什么提示吗?
    • @Silmaril 我也发布了问题,请回答以便我关闭它:*.com/questions/39573514/…
    • @Silmaril 对我不起作用。将“myBody”转换为{ myBody: '' }。斯威夫特 3. Alamofire 4.0.0.
    【解决方案2】:

    你可以这样做:

    1. 我创建了一个单独的请求 Alamofire 对象。
    2. 将字符串转换为数据
    3. 将数据放入httpBody

      var request = URLRequest(url: URL(string: url)!)
      request.httpMethod = HTTPMethod.post.rawValue
      request.setValue("application/json", forHTTPHeaderField: "Content-Type")
      
      let pjson = attendences.toJSONString(prettyPrint: false)
      let data = (pjson?.data(using: .utf8))! as Data
      
      request.httpBody = data
      
      Alamofire.request(request).responseJSON { (response) in
      
      
          print(response)
      
      }
      

    【讨论】:

    • 这应该是公认的答案。它很简单,完全符合需要,并且没有不必要的扩展或转换。谢谢,伙计。
    • P.S.我已经“借用”了您对另一个问题的回答 - *.com/a/42411188/362305
    • 什么是出席率,能不能发一个更完整的sn-p
    • @SyraKozZ 不管出勤率是多少,唯一认为重要的是 pjson 是一个 json 字符串。您可以将任何 json 字符串放在那里。
    【解决方案3】:

    如果你使用Alamofire,将encoding类型设置为URLEncoding.httpBody就足够了

    这样,您可以在 httpbody 中将数据作为字符串发送,尽管您在代码中将其定义为 json。

    它对我有用..

    更新了 Badr Filali 的问题

    var url = "http://..."
    let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
    let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
    
    let url =  NSURL(string:"url" as String)
    
    request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: _headers).responseJSON(
        completionHandler: { response in response
            let jsonResponse = response.result.value as! NSDictionary
            
            if jsonResponse["access_token"] != nil
            {
                access_token = String(describing: jsonResponse["accesstoken"]!)
            }
        })
    

    【讨论】:

    • 我会更新我的答案并编写使用过的代码,因为我无法从这里找到如何编写代码作为评论。抱歉迟到了。@Badr Filali
    • 为我工作,但我的身体需要是 JSON,所以,我将编码:URLEncoding.httpBody 更改为编码:JSONEncoding.default,一切正常。
    • 是的@AngeloPolotto 感谢您的贡献:) 这是关于编码类型的服务。可以根据您的 REST API 用作 URLEncoding 或 JSONEncoding。
    • 感谢您的回答。但我面临的问题是当我发送一个变量而不是double quotes strings 并得到错误代码400。我该如何解决?
    • 你能把示例代码发给我吗?我可以通过这种方式更好地帮助你@viper
    【解决方案4】:

    我修改了@Silmaril 的答案以扩展 Alamofire 的经理。 此方案使用 EVReflection 直接序列化对象:

    //Extend Alamofire so it can do POSTs with a JSON body from passed object
    extension Alamofire.Manager {
        public class func request(
            method: Alamofire.Method,
            _ URLString: URLStringConvertible,
              bodyObject: EVObject)
            -> Request
        {
            return Manager.sharedInstance.request(
                method,
                URLString,
                parameters: [:],
                encoding: .Custom({ (convertible, params) in
                    let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
                    mutableRequest.HTTPBody = bodyObject.toJsonString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                    return (mutableRequest, nil)
                })
            )
        }
    }
    

    然后你可以这样使用它:

    Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)
    

    【讨论】:

      【解决方案5】:

      基于Illya Krit的回答

      详情

      • Xcode 版本 10.2.1 (10E1001)
      • 斯威夫特 5
      • Alamofire 4.8.2

      解决方案

      import Alamofire
      
      struct BodyStringEncoding: ParameterEncoding {
      
          private let body: String
      
          init(body: String) { self.body = body }
      
          func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
              guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
              guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
              urlRequest.httpBody = data
              return urlRequest
          }
      }
      
      extension BodyStringEncoding {
          enum Errors: Error {
              case emptyURLRequest
              case encodingProblem
          }
      }
      
      extension BodyStringEncoding.Errors: LocalizedError {
          var errorDescription: String? {
              switch self {
                  case .emptyURLRequest: return "Empty url request"
                  case .encodingProblem: return "Encoding problem"
              }
          }
      }
      

      用法

      Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
           print(response)
      }
      

      【讨论】:

      • Спасибо вам большое !
      【解决方案6】:

      如果您想在请求中将字符串作为原始正文发布

      return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
                  (convertible, params) in
                  let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
      
                  let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
                  mutableRequest.HTTPBody = data
                  return (mutableRequest, nil)
              }))
      

      【讨论】:

      【解决方案7】:

      我已经为字符串中的数组完成了它。此解决方案针对正文中的字符串进行了调整。

      Alamofire 4 的“原生”方式:

      struct JSONStringArrayEncoding: ParameterEncoding {
          private let myString: String
      
          init(string: String) {
              self.myString = string
          }
      
          func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
              var urlRequest = urlRequest.urlRequest
      
              let data = myString.data(using: .utf8)!
      
              if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
                  urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
              }
      
              urlRequest?.httpBody = data
      
              return urlRequest!
          }
      }
      

      然后通过以下方式提出您的请求:

      Alamofire.request("your url string", method: .post, parameters: [:], encoding: JSONStringArrayEncoding.init(string: "My string for body"), headers: [:])
      

      【讨论】:

        【解决方案8】:

        我使用@afrodev 的答案作为参考。就我而言,我将函数的参数作为必须在请求中发布的字符串。所以,这里是代码:

        func defineOriginalLanguage(ofText: String) {
            let text =  ofText
            let stringURL = basicURL + "identify?version=2018-05-01"
            let url = URL(string: stringURL)
        
            var request = URLRequest(url: url!)
            request.httpMethod = HTTPMethod.post.rawValue
            request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
            request.httpBody = text.data(using: .utf8)
        
            Alamofire.request(request)
                .responseJSON { response in
                    print(response)
            }
        }
        

        【讨论】:

        • 你到底没有得到什么?
        【解决方案9】:
        func paramsFromJSON(json: String) -> [String : AnyObject]?
        {
            let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
            var jsonDict: [ String : AnyObject]!
            do {
                jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
                return jsonDict
            } catch {
                print("JSON serialization failed:  \(error)")
                return nil
            }
        }
        
        let json = Mapper().toJSONString(loginJSON, prettyPrint: false)
        
        Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)
        

        【讨论】:

        • 什么是映射器?
        【解决方案10】:

        我的情况,使用 content-type:"Content-Type":"application/x-www-form-urlencoded" 发布 alamofire,我不得不更改 alampfire 发布请求的编码

        来自:JSONENCODING.DEFAULT 到:URLEncoding.httpBody

        这里:

        let url = ServicesURls.register_token()
            let body = [
                "UserName": "Minus28",
                "grant_type": "password",
                "Password": "1a29fcd1-2adb-4eaa-9abf-b86607f87085",
                 "DeviceNumber": "e9c156d2ab5421e5",
                  "AppNotificationKey": "test-test-test",
                "RegistrationEmail": email,
                "RegistrationPassword": password,
                "RegistrationType": 2
                ] as [String : Any]
        
        
            Alamofire.request(url, method: .post, parameters: body, encoding: URLEncoding.httpBody , headers: setUpHeaders()).log().responseJSON { (response) in
        

        【讨论】:

          【解决方案11】:
          let parameters = ["foo": "bar"]
                        
              // All three of these calls are equivalent
              AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
              AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
              AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
              
              
          

          【讨论】:

            【解决方案12】:

            Xcode 8.X 、Swift 3.X

            易于使用;

             let params:NSMutableDictionary? = ["foo": "bar"];
                        let ulr =  NSURL(string:"http://mywebsite.com/post-request" as String)
                        let request = NSMutableURLRequest(url: ulr! as URL)
                        request.httpMethod = "POST"
                        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                        let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
            
                        let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                        if let json = json {
                            print(json)
                        }
                        request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
            
            
                        Alamofire.request(request as! URLRequestConvertible)
                            .responseJSON { response in
                                // do whatever you want here
                               print(response.request)  
                               print(response.response) 
                               print(response.data) 
                               print(response.result)
            
                        }
            

            【讨论】: