ios 使用 Alamofire 在正文中使用简单字符串的 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27855319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:17:20  来源:igfitidea点击:

POST request with a simple string in body with Alamofire

ioshttpswiftrequestalamofire

提问by Karl

how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app?

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

As default Alamofire needs parameters for a request:

默认情况下,Alamofire 需要请求参数:

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

These parameters contain key-value-pairs. But I don't want to send a request with a key-value string in the HTTP body.

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

I mean something like this:

我的意思是这样的:

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

回答by Silmaril

Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])already contains "foo=bar" string as its body. But if you really want string with custom format. You can do this:

您的示例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)
        }))

Note: parametersshould not be nil

注意:parameters不应该nil

UPDATE (Alamofire 4.0, Swift 3.0):

更新(Alamofire 4.0,Swift 3.0):

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncodingprotocol.

在 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: [:])

回答by afrodev

You can do this:

你可以这样做:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    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)
    
    }
    
  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)
    
    }
    

回答by Cemal BAYRI

If you use Alamofire, it is enough to encoding type to "URLEncoding.httpBody"

如果您使用 Alamofire,将类型编码为“URLEncoding.httpBody”就足够了

With that, you can send your data as a string in the httpbody allthough you defined it json in your code.

有了它,您可以将数据作为字符串发送到 httpbody 中,尽管您在代码中定义了它 json。

It worked for me..

它对我有用..

UPDATED for

更新为

  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"]!)

        }

    })

回答by raf

I modified @Silmaril's answer to extend Alamofire's Manager. This solution uses EVReflection to serialize an object directly:

我修改了@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)
            })
        )
    }
}

Then you can use it like this:

然后你可以像这样使用它:

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

回答by J.R

If you want to post string as raw body in request

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

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)
        }))

回答by Illya Krit

I have done it for array from strings. This solution is adjusted for string in body.

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

The "native" way from Alamofire 4:

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!
    }
}

And then make your request with:

然后提出您的请求:

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

回答by GeoSD

I've used answer of @afrodev as reference. In my case I take parameter to my function as string that have to be posted in request. So, here is the code:

我使用@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)
    }
}

回答by Vasily Bodnarchuk

Based on Illya Krit's answer

基于Illya Krit的回答

Details

细节

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5
  • Alamofire 4.8.2
  • Xcode 版本 10.2.1 (10E1001)
  • 斯威夫特 5
  • 阿拉莫火 4.8.2

Solution

解决方案

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"
        }
    }
}

Usage

用法

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

回答by AndrewK

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)

回答by IsPha

My case, posting alamofire with content-type: "Content-Type":"application/x-www-form-urlencoded", I had to change encoding of alampfire post request

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

from : JSONENCODING.DEFAULT to: URLEncoding.httpBody

从:JSONENCODING.DEFAULT 到:URLEncoding.httpBody

here:

这里:

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