简体   繁体   English

如何使用 Alamofire 在获取请求中发送 JSON 正文

[英]How to send a JSON body in a get request with Alamofire

I'm facing a problem since 3 weeks now, I'm using an API pretty particular which need a JSON object as body in a GET request.自 3 周以来,我一直面临一个问题,我正在使用一个非常特殊的 API,它需要一个 JSON 对象作为 GET 请求中的正文。 And I think that it's the main problem我认为这是主要问题

I tried to custom my encoding with ParameterEncoding thanks the Alamofire documentation and all the help provide in Stack Overflow and still no success.感谢 Alamofire 文档和 Stack Overflow 中提供的所有帮助,我尝试使用 ParameterEncoding 自定义我的编码,但仍然没有成功。

When I make my request with Postman or with curl in my terminal, there is no problem but when I develop in swift with Alamofire, I get an internal error 500 or nothing passed in my response (when I set my parameter in my request function with the keyword encoding: JSONEncoding.default).当我使用 Postman 或在我的终端中使用 curl 发出请求时,没有问题,但是当我使用 Alamofire 快速开发时,我收到内部错误 500 或在我的响应中没有传递任何内容(当我在我的请求函数中设置我的参数时关键字编码:JSONEncoding.default)。

Here is the curl exemple:这是卷曲的例子:

curl -X GET https://blih.epitech.eu/user/repositories -H 'Content-Type: application/json' -d '{"user": account, "signature": password}' curl -X GET https://blih.epitech.eu/user/repositories -H 'Content-Type: application/json' -d '{"user": account, "signature": password}'

Here is the sample of my code:这是我的代码示例:

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

The 'JSONStringArrayEncoding' is a structure with my Custom Encoding: '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
    }
}

I expect to have a json Array when the request is successsful:当请求成功时,我希望有一个 json 数组:

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

But I get an internal error 500.但是我得到一个内部错误 500。

Thank you in advance for your help.预先感谢您的帮助。

Just replace JSON.encoding -> URLEncoding只需替换JSON.encoding -> URLEncoding

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

As you have mentioned that, your request is working using postman or curl in terminal.正如您所提到的,您的请求正在终端中使用 postman 或 curl 工作。 Below is the result I'm getting下面是我得到的结果

在此处输入图像描述

As pointed by @Glenn, result of visiting browser with url blih.epitech.eu/user/repositories show result like below正如@Glenn 所指出的,使用 url blih.epitech.eu/user/repositories访问浏览器的结果显示结果如下

在此处输入图像描述

I believe, there is something wrong with the url you're requesting to.我相信,您请求的网址有问题。

EDITED:编辑:

See the below image to see the why it is working with curl请参阅下图以了解它与 curl 一起工作的原因

在此处输入图像描述

Try your request as post once and add content-type = application/x-www-form-urlencoded I am not sure but it might help.尝试将您的请求作为帖子发送一次并添加content-type = application/x-www-form-urlencoded我不确定,但它可能会有所帮助。

Try this:试试这个:

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

OUTPUT:输出:

{ error = "Bad token"; { error = "坏令牌"; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM