SolvedMoya Not able to get URLEncoding working correctly when there is "?" and the method is "POST"

I am using the last version of Moya and Alamofire with Swift 3

I am having trouble when the method is "POST" and there is url encoding

The url must be:

but it is converted to be:

which is not working and giving 400 error on the server

where can I find this conversion and stop it for the requests ?

Here is the code i used:

enum MyService {
	case products(categorytId: Int)

extension MyService : TargetType {
    var base: String { return Constants.MyServiceURL }
    var baseURL: URL { return URL(string: base)! }
    public var task: Task {
        return .request

    var path : String {
        switch self {
        // i tried with and without them, changing the parameters down below
        case .products(let id_category): 
            return "products?id_category=\(id_category)"

    var parameterEncoding: ParameterEncoding {
	    switch self {
	        case .products:
	        	//return MyURLEncoding.queryString
	            return URLEncoding.queryString
	            return JSONEncoding.default 

    var parameters : [String : Any]? {
        switch self {
        // here I tried to add them for Testing purpose, i tried with and without them
        case .products(let id_category):
            var params: [String: Any] = [:]
            params["id_category"] = id_category
            return params
            return nil

    // The method must be always post always
    var method : Moya.Method {
        return .post;

    var sampleDate : Data {
            return Data()
36 Answers

✔️Accepted Answer

try use this

var baseURL: URL{
        switch self {
        case .chagePassword(_,_,let token):
             return URL(string: "base_url?token=\(token)")!
            return URL(string: "base_url")!

var path:String{
        switch self {
        case .chagePassword:
            return "/api/update-password"

and url request will like this "base_url/api/update-password?token="114149814189"

Other Answers:

the problem is instead of getting this as
URL: "http://myWebSErvice/products?id_category=30"

I get this: %3F
URL: "http://myWebSErvice/products%3Fid_category=30"

and when the "?" becomes "%3F" , the webservice throws error this "A potentially dangerous Request.Path value was detected from the client (?)."

What i want is only to send the request with ? not with %3F

@iballan Looks like I have found solution. You should use own Endpoint and url stay correct without changing from '?' to '%3F'
This my real method that works for this situation

    let authPlugin = AccessTokenPlugin(token: token)
    let provider = RxMoyaProvider<Service>(endpointClosure: {target in
      return Endpoint(
        url: "\(target.baseURL)\(target.path)",
        sampleResponseClosure: { .networkResponse(200, target.sampleData) },
        method: target.method,
        parameters: target.parameters,
        parameterEncoding: target.parameterEncoding
    }, plugins: [authPlugin])

For me it didn't get yet.
The difference is that I'm using .get

But the problem still happens, it converts the "?" to "%3F"

Related Issues:

Moya Not able to get URLEncoding working correctly when there is "?" and the method is "POST"
try use this and url request will like this base_url/api/update-password?token=114149814189 ...
Moya How to send String JSON Array as parameter?
Here is an UNTESTED example that at least compiles. I want to send String JSON array as parameter bu...
Moya How do I create a path with a '?' within the string?
@pete183 Yes URLEncoding.default will put your parameters in the url 😉 Moya Version - 8.0.5 When I ...
Moya Moya support for Swift 4 with RxSwift ?
Hey again @aninhakrieger @linbx08 I am using the following pods ...
Alamofire “Use Legacy Swift Language Version” with pod 'Alamofire', '~> 4.0'
Have you tried this? I have to convert my project from X...
Alamofire iOS 13.3.1 dyld: Library not loaded
Are you using a non-developer Apple ID to install the app to your phone? It looks like iOS 13.3.1 ha...
Alamofire Extra argument 'method' in call
I'm getting the same issue with the same error message (Extra argument 'method' in call) with correc...
Alamofire Sending GET with JSON in body gets Timeout error
I figured out my problem In my Router I had my GET requests using JSONEncoding: urlRequest = try JSO...
Alamofire Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error
Hello I solved the problem with: I pupdated my question in StackOverflow I am using the version 4.3....
Alamofire Module compiled with Swift 4.2.1 cannot be imported by the Swift 5.0
I'm having almost the exact the same issue: Module compiled with Swift 4.2.1 cannot be imported by t...
Alamofire [WIP] Swift 3.0 Migration
install compatibility with cocoapods? @kcharwood EDIT: use Alamofire - Swift 3.0 The initial migrati...
Alamofire validate() "eats" response data
So to all of you convinced the data is's not debugPrint(response) without validate(): debu...
Alamofire Version 3.5 not found on Cocoapods Specs
Until this is resolved you can use the 3.5.0 release by specifying the tag directly pod 'Alamofire' ...
axios Axios catch error returns javascript error not server response
I have exactly the same environment Try this: Modify from console.log(error) to console.log(
scrapy ' error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 '
@euler16 for scrapy with Python 3 you'll need with Python 2 you'll need I wanted to install scrapy i...
laradock Mysql. The server requested authentication method unknown to the client [caching_sha2_password]
alter user 'username'@'localhost' identified with mysql_native_password by 'password'; would fix it....
react navigation screenIsActive prop / componentDidFocus event for TabNavigator items
It probably makes sense to add lifecycle hooks to screens In one of my Tabs i need to load Data from...
meteor [] Error: ENFILE: file table overflow
I was getting the same after an upgrade to macOS Sierra Turns out macOS have a harsh limit on number...
ipython Last jedi release (0.18.0) is incompatible with ipython (7.19 and 7.18 tested); reason - column arg was deprecated, and now removed
As a temporary fix for anyone just trying to get things working again: It would be really nice if yo...
material ui Module not found: Can't resolve 'material-ui-icons/Menu' Martial Next
For anyone else experiencing this issue: npm install @material-ui/icons
laravel dompdf (1/1) ErrorException Non-static method Barryvdh\DomPDF\PDF::loadView() should not be called statically
This happens because you are namespacing the wrong PDF class You are namespacing Barryvdh\DomPDF\PDF...
webpacker localIdentName option moved in css-loader configuration
I faced same issue after upading css-loader but I solved it If you check css-loader readme ...
react navigation Send data back from child screen?
@itswaze You can do something along these lines to pass back from the child screen ...
react navigation How to goBack from nested StackNavigator?
@dhruvparmar372 According to the NOTE in the doc a navigator's navigation prop may not have the help...
axios POST request works in Browser but not on Node
This might be considered a duplicate of #789 I was able to use the form-data package with Axios in n...
react navigation Best pattern for a 'Save' button in the header
Try setting your component instance's handleSave function as a navigation state parameter after the ...
DefinitelyTyped [@types/react] RefObject.current should no longer be readonly
It's not It'a intentionally left readonly to ensure correct usage even if it's not frozen ...
react native navigation [V3][Android] FATAL EXCEPTION: create_react_context
OK after a good night of sleep I've found why I was having this issue In the I ...
ts node Custom typings not working with ts-node 8.0.2
When using with ts-node you have to add --files flag After updating to ts-node version 8.0.2 the cus...
ohmyzsh compinit:503: no such file or directory: /usr/local/share/zsh/site-functions/_brew
Per #9602 (comment) brew cleanup fixed it for me I am using Apple M1 When I added this line: export ...
laradock SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client
+1 I'm having the same problem here. Info: Docker version ($ docker --version): Docker version 17.12...
vagrant vagrant box update - Fails with 404 Not Found error
A workarround to add in your Vagrantfile: Vagrant version Host operating system Ubuntu 16.04.3 LTS G...
vagrant vagrant --help displays a rubygems error
To fix this error: Vagrant version Host operating system Expected behavior vagrant and vagrant --hel...
date fns Can't resolve 'date-fns/_lib/format/longFormatters'
You probably forgot to install date-fns or Code: import DateFnsUtils from '@date-io/date-fns'; ...
virtualenv Error creating virtualenv with python3.6
The original poster's problem is due to not having the 'python3.6-venv' package installed ...
provider A Product was used after being disposed. flutter: Once you have called dispose() on a Product, it can no longer be used.
Oh I see what you're doing Don't: DO: i have a ChangeNotifireProvider that such that i do pushReplac...
react navigation Reset to nested route, "There is no route defined for..."
A quick workaround (not heavily tested): set the key property to null on your action. ...
axios Adding headers to method
Edit: I had to add Authorization to allowed headers in my CORS filter @jffernandez I'm having the sa...
axios Adding Retry Parameter
@mericsson I am too in need of exponential backoff when retrying I've put together the following whi...
homebrew openjdk Cask adoptopenjdk8 exists in multiple taps
I think AdoptOpenJDK8 should be removed from the homebrew-cask-versions repo Somone(TM) should proba...
nativescript cli TNS doctor doesn't recognize Xcode (High Sierra)
HI @philipfeldmann Can yhou please run xcodebuild -version and paste the output? May be Xcode is ins...
axios BaseURL not being used
Please IGNORE THIS ISSUE Found the problem: I was setting baseUrl but it should be baseURL. ...
axios How to ignore SSL issues
You can configure axios to use a custom agent and set rejectUnauthorized to false for that agent: Ho...
ipython NameError: name 'sys' is not defined
Ok that was easy The Jedi release on 12/25 version 0.18.0 is breaking tab completion pip install --u...
axios How to send Raw http for Instagram Authentication?
Yes StringClient uses the application/x-www-form-urlencoded format by default while axios uses appli...
vuetify [Bug Report] Could not find a declaration file for module 'vuetify/lib'
@KaelWD Thank you for the link More specifically this comment helped me out to properly update my ts...
axios CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource
My solution is axios.get('' + yourUrl) update: doesn't work ...
runtime An assembly specified in the application dependencies manifest (RhWeb.deps.json) was not found
I also hit this For me it had to do with the use of in my .csproj when running in an environment tha...
react navigation Drawer changes in #1803 causes undocumented breaking changes to drawernavigators
Adding to the drawer configs fixed the issue for me. Current Behavior create a single drawer navigat...