简体   繁体   English

使用Moya和Alamofire时使用参数编码的发布请求错误

[英]Post request error with parameter encode when use moya and alamofire

I use the moya make the post request,but when I send the post , the server give me an error, it can't decoding the body parameters.I use URLEncoding.default to encode the parameters like this 我使用moya发出发布请求,但是当我发送发布时,服务器给我一个错误,它无法解码主体参数。我使用URLEncoding.default对这样的参数进行编码

public var parameterEncoding: ParameterEncoding {
    return URLEncoding.default
}

It will set the content-type application/x-www-form-urlencoded, and the server accept content type is same too 它将设置内容类型application / x-www-form-urlencoded,并且服务器接受的内容类型也相同

if parameters is a dictionary like this {"a":"b"} ,that is working well, but if dictionary contained array or another dictionary ,the server can't get the parameters from request body. 如果parameter是一个像这样的字典“ {” a“:” b“},则效果很好,但是如果字典包含数组或另一个字典,则服务器无法从请求主体获取参数。

EX: EX:

{
   "a":"xxx",
   "b":[
          "xxxxx",
          "xxxxx"
       ]
}

alamofire will encode this like "a"="xxx"&b[]=xxxx&b[]=xxx alamofire会将其编码为“ a” =“ xxx”&b [] = xxxx&b [] = xxx

but the server expect a=xxx&b[0]=xxx&b[1]=xxxx 但服务器期望a = xxx&b [0] = xxx&b [1] = xxxx

how to solve this problem ? 如何解决这个问题呢 ?

You can build the parameter string manually, and then link the parameter string to Url string. 您可以手动构建参数字符串,然后将参数字符串链接到Url字符串。 Finally, just make request with url by Alamofire, without any parameters(they are in url already). 最后,只需通过Alamofire使用url进行请求,而无需任何参数(它们已经在url中)。

The way to build parameter string: 建立参数字符串的方式:

    let dict = ["a":"xxx","b":["xxx","xxxxxxx"]] as [String : Any]
    var paramString = ""

    for key in dict.keys {
        let value = dict[key]
        if let stringValue = value as? String {
            paramString += "&\(key)=\(stringValue)"
        }
        else if let arr = value as? Array<String> {
            for i in 0 ... arr.count - 1 {
                paramString += "&\(key)[\(i)]=\(arr[i])"
            }
        }
        else{
            //other type?
        }
    }

    if paramString.characters.count > 0 {
        paramString = paramString.substring(from: paramString.index(paramString.startIndex, offsetBy: 1))
    }

    print(paramString)
    //output is:  b[0]=xxx&b[1]=xxxxxxx&a=xxx

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

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