【问题标题】:How to add urlencoded parameter to httpBody in urlRequest如何在 urlRequest 中将 urlencoded 参数添加到 httpBody
【发布时间】:2019-06-27 06:23:35
【问题描述】:

我为 alamofire 请求创建了一个通用类 我想发送参数为aplication/x-www-form-urlencoded 如何将参数添加到我的urlRequest

我已经设法使用下面的代码将参数作为application/json 添加到 urlRequest

    do {
            urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
        } catch {
            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
        }

aplication/x-www-form-urlencoded

我需要类似的东西

这是我的参数

case .ewalletData :
        return [K.APIParameterKey.token :"OP8JHOEOZ5KJW1X",K.APIParameterKey.fromMobile:"true",K.APIParameterKey.adminName:"binaryecom",K.APIParameterKey.limit:"100",K.APIParameterKey.offset:"0",K.APIParameterKey.userName:"OC6DGH"]

【问题讨论】:

    标签: ios alamofire urlencode swift5 urlrequest


    【解决方案1】:

    这是它在 swift 4 中为我工作的代码: let postString = "your parameter="+value+"&your parameter="+value request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request, completionHandler: completionHandle) task.resume()

    【讨论】:

    • 我这个格式的参数public typealias Parameters = [String: Any]想把这个加到httpBody中
    • 我会添加另一个答案检查一下。
    【解决方案2】:

    试试这个:

            guard let request_url = URL(string: Url) else { return }
            let parameterDictionary = ["your parameter" : value]
            var request = URLRequest(url: request_url)
            request.httpMethod = "POST"
    
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("aplication/x-www-form-urlencoded", forHTTPHeaderField: "String")
            guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
                return
            }
            request.httpBody = httpBody
    

    【讨论】:

    • 你不需要单独写答案。您可以编辑现有的并附加您的答案。
    • 我想让其他人知道在 body 中传递参数的不同方式。
    • 嗨@ZahraAsqarzade,当 Content-Type = Application/json 时,我已成功获得响应。我希望aplication/x-www-form-urlencoded 与您在上面示例中提供的参数相同
    • 再次设置标题:request.setValue("aplication/x-www-form-urlencoded", forHTTPHeaderField: "String")
    • 我们还需要添加guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else { return } 吗?你能帮我编辑一下答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    相关资源
    最近更新 更多