Moya: Parameter Encoding for POST method not working.

Created on 8 Jun 2017  路  3Comments  路  Source: Moya/Moya

Swift 3.1
Moya 8.0.5

Is it possible to place parameters in URL when I have a request with POST method?

My goal is to create a request with parameters included in URL. So the request should look like this:

POST https://google.com/123/somePath?parameterId=someId

Unfortunately, when I create request with POST method all parameters are placed outside URL. I made some tests and I've discovered that when I change the method to GET, then all works fine.

screen shot 2017-06-08 at 11 24 21

Below my code and cURL for both requests:

github url: https://github.com/k8mil/MoyaBaseURL

enum MyApi {
    case postWithURLParameters
}

extension MyApi: TargetType {

    var baseURL: URL {
        return URL(string: "https://google.com")!
    }

    var path: String {
        return "/123/somePath"
    }

    var method: Moya.Method {
        //return .get //it works
        return .post
    }

    var parameters: [String: Any]? {
        return ["parameterId": "someId"]
    }

    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }

    var sampleData: Data {
        return Data()
    }

    var task: Task {
        return .request
    }
}

@objc func doRequest() {
    provider.request(MyApi.postWithURLParameters) {
        result in
        print(result)
    }
}
curl -H "Host: google.com" -H "Accept-Language: en;q=1.0" -H "Accept: */*" -H "User-Agent: MoyaBaseURL/1.0 (k8mil.MoyaBaseURL; build:1; iOS 10.3.0) Alamofire/4.4.0" --compressed https://google.com/123/somePath?parameterId=someId
curl -H "Host: google.com" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" -H "Accept: */*" -H "User-Agent: MoyaBaseURL/1.0 (k8mil.MoyaBaseURL; build:1; iOS 10.3.0) Alamofire/4.4.0" -H "Accept-Language: en;q=1.0" --data-binary "parameterId=someId" --compressed https://google.com/123/somePath
question

Most helpful comment

Hey @k8mil. You are right - by default POST method would add parameters to the body. But there is an option to brute-force it in the query string: you would have to use URLEncoding(destination: .queryString) as your parameterEncoding. More on this matter you can find here.

All 3 comments

According to this:

https://stackoverflow.com/questions/14551194/how-are-parameters-sent-in-an-http-post-request

It seems to be specially designed for POST.

Hey @k8mil. You are right - by default POST method would add parameters to the body. But there is an option to brute-force it in the query string: you would have to use URLEncoding(destination: .queryString) as your parameterEncoding. More on this matter you can find here.

@sunshinejr
Thanks for pointing that. However, finally I'll stay with default way, so my POSTplace the parameters into request body. :)

Was this page helpful?
0 / 5 - 0 ratings