【问题标题】:How to send a JSON body in a get request with Alamofire如何使用 Alamofire 在获取请求中发送 JSON 正文
【发布时间】:2019-09-15 10:47:57
【问题描述】:

自 3 周以来我一直面临一个问题,我正在使用一个非常特殊的 API,它需要一个 JSON 对象作为 GET 请求中的主体。我认为这是主要问题

感谢 Alamofire 文档和 Stack Overflow 中提供的所有帮助,我尝试使用 ParameterEncoding 自定义编码,但仍然没有成功。

当我在终端中使用 Postman 或 curl 发出请求时,没有问题,但是当我使用 Alamofire 快速开发时,我收到内部错误 500 或响应中没有传递任何内容(当我在我的带有关键字 encoding 的请求函数:JSONEncoding.default)。

这是 curl 的例子:

curl -X 获取https://blih.epitech.eu/user/repositories -H '内容类型:应用程序/json' -d '{"user": 帐号, "signature": 密码}'

这是我的代码示例:

/// swift 5
let userString = #"{"user":"\#(account)","signature":"\#(signaturePassword)"}"#
let urlString = "https://blih.epitech.eu/repositories"

Alamofire.request(urlString, method: .get, parameters: [:], encoding: JSONStringArrayEncoding.init(string: userString), headers: nil)
    .responseJSON { (response) in
        debugPrint(response)
}

“JSONStringArrayEncoding”是我的自定义编码结构:

struct JSONStringArrayEncoding: ParameterEncoding {
    private let myString: String

    init(string: String) {
        self.myString = string
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        let data = Data(myString.utf8)

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = data

        return urlRequest
    }
}

我希望在请求成功时有一个 json 数组:

{
"message": "Listing successful",
    "repositories": {
        "aaaa": {
            "uuid": "e3a6bea1-c581-5fde-a3a8",
            "url": "https://blih.epitech.eu/repository/aaa"
        }
    }
}

但我收到内部错误 500。

提前感谢您的帮助。

【问题讨论】:

  • 您是否尝试过在浏览器中访问您的网址? blih.epitech.eu/user/repositories
  • 当然,我在 Swift 中开发时有时会遇到同样的错误,但是当我使用 postman 或 curl 命令进行测试时,没有问题。我应该准确地说您需要在正文中发送一个对象:{"user":"test@epitech.eu", "signature":"long-token"}

标签: ios swift alamofire


【解决方案1】:

只需替换JSON.encoding -> URLEncoding

Alamofire.request(path,method: .get, parameters: params, encoding: URLEncoding.default, headers: nil)

【讨论】:

    【解决方案2】:

    正如您所提到的,您的请求正在使用 postman 或 curl 在终端中工作。下面是我得到的结果

    正如@Glenn 所指出的,使用 url blih.epitech.eu/user/repositories 访问浏览器的结果如下所示

    我相信,您请求的网址有问题。

    已编辑:

    查看下图以了解它与 curl 一起使用的原因

    尝试将您的请求作为帖子一次并添加 content-type = application/x-www-form-urlencoded 我不确定,但它可能会有所帮助。

    【讨论】:

    • 你不应该这样暴露你的签名。它可能导致数据泄露。
    • 谢谢,那我应该删除我的帖子吗?
    • 只删除您的评论,我相信,curl中的-d用于在帖子类型请求中发布数据
    【解决方案3】:

    试试这个:

    let url = "https://blih.epitech.eu/user/repositories"
    let param = ["user":"asdfdsf",
        "signature":"password"]
    if let jsonData = try? JSONEncoder().encode(param) {
    
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
    
        Alamofire.request(request).responseJSON {
            (response) in
            debugPrint(response)
        }
    }
    

    输出:

    { error = "错误令牌"; }

    【讨论】:

    • 我仍然收到 500 错误:状态代码:500,标题 { Connection = ( "keep-alive" ); “内容长度”=(759); “内容类型”=(“文本/html;字符集=UTF-8”);日期 = ("2019 年 4 月 26 日星期五 07:23:21 GMT");服务器 = ( "nginx/1.10.2" ); } } [结果]: FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 5."
    猜你喜欢
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2020-10-04
    • 2015-10-28
    • 1970-01-01
    • 2022-01-22
    • 2020-05-23
    相关资源
    最近更新 更多