-2

This is my url,

http://api.theahsanzaman.info/token?username=haris123@gmail.com&password=Haris@123&grant_type=password

I want it to encode it like this way,

http://api.theahsanzaman.info/token?username%3Dharis123%40gmail.com%26password%3DHaris%40123%26grant_type%3Dpassword

The = sign should be replace by %3D The & sign should be replace by %26 The @ sign should be replace by %40

How can i change my ur to this?

Hamza
  • 231
  • 1
  • 8
  • 22
  • 2
    Possible duplicate of [Swift - encode URL](https://stackoverflow.com/questions/24551816/swift-encode-url) – Jacob Lange Apr 17 '18 at 16:58
  • That's a very strange encoding. Why do you want to do that? This is not how `application/x-www-form-urlencoded` requests work. You generally do want the request in the form of `http://example.com?key1=value1&key2=value2`. I'm suspicious about the premise behind this question... – Rob Apr 17 '18 at 16:58
  • Or are you trying to encode this so you can then embed this as a value in another request (in which case, we'd be better off answering that broader question than this one). – Rob Apr 17 '18 at 17:04
  • Restricted from the server side thats why i have to do so. @Rob – Hamza Apr 17 '18 at 17:04
  • I tried this on your "I want to encode it like this way" string (calling it `s`): `let url = URL(string:s)`. I got an URL (i.e. not `nil`). So it's hard to see what the problem is. If you want to the URL to be that, make it be that. Turn the initial URL into a string, perform the desired substitutions, turn the result back into a URL. What's the hard part? – matt Apr 17 '18 at 17:11
  • "Restricted from the server side" ... We can show you how to do what you want, but the whole idea suggests some deep misunderstanding somewhere (why the web service doesn't conform to standards, why you're including a password in a URL which introduces security problems, etc.). We're not trying to be difficult, but this is code smell for some deeper problem and you appear to be reluctant to provide a broader context... – Rob Apr 17 '18 at 17:17
  • Order shouldn't be important, and if you construct yourself the URL, `URLComponents` and `URLQueryItems` should be a good solution. – Larme Apr 17 '18 at 17:34

1 Answers1

0

If you want to do that, remove the characters to be percent escaped from the .urlQueryAllowed character set and percent encode accordingly:

var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "=@&")

let result = urlString.addingPercentEncoding(withAllowedCharacters: allowed)
Rob
  • 415,655
  • 72
  • 787
  • 1,044