Post request error with parameter encode when use

2019-09-14 15:33发布

问题:

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

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

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.

EX:

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

alamofire will encode this like "a"="xxx"&b[]=xxxx&b[]=xxx

but the server expect a=xxx&b[0]=xxx&b[1]=xxxx

how to solve this problem ?

回答1:

You can build the parameter string manually, and then link the parameter string to Url string. Finally, just make request with url by Alamofire, without any parameters(they are in url already).

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