Post request error with parameter encode when use moya and alamofire

杀马特。学长 韩版系。学妹 提交于 2019-12-12 05:42:00

问题


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


来源:https://stackoverflow.com/questions/45482628/post-request-error-with-parameter-encode-when-use-moya-and-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!