Skip to content

Instantly share code, notes, and snippets.

@brunabaudel
Last active September 10, 2019 04:36
Show Gist options
  • Save brunabaudel/90a6873d2c3df6caeb89f8b7afc9adce to your computer and use it in GitHub Desktop.
Save brunabaudel/90a6873d2c3df6caeb89f8b7afc9adce to your computer and use it in GitHub Desktop.
Proxy configuration is not working on Swift 5 (using Charles Proxy)
// The Proxy is configurated but the code isn't using it somehow.
// You can verify this by changing the kCFNetworkProxiesHTTPProxy and kCFNetworkProxiesHTTPPort values,
// and you're going to get the same output when you expect it'd fail.
url request = Optional("https://ip.seeip.org/jsonip")
headers request = Optional(["Accept": "application/json"])
response = Optional(<NSHTTPURLResponse: 0x6000032aca60> { URL: https://ip.seeip.org/jsonip } { Status Code: 200, Headers {
Connection = (
close
);
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Tue, 10 Sep 2019 04:02:06 GMT"
);
Server = (
"openresty/1.11.2.5"
);
"Transfer-Encoding" = (
Identity
);
} })
data body = Optional("{\"ip\":\"172.217.162.174\"}\n")
import Foundation
class URLSessionProxy: NSObject, URLSessionDelegate {
func doRequest() {
let configuration = URLSessionConfiguration.default
configuration.connectionProxyDictionary = [
kCFNetworkProxiesHTTPEnable: true,
kCFNetworkProxiesHTTPProxy: "localhost",
kCFNetworkProxiesHTTPPort: "8888",
]
var request = URLRequest(url: URL(string: "https://ip.seeip.org/jsonip")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
.dataTask(with: request, completionHandler: { (data, response, error) in
if error == nil {
print("url request = ", request.url?.absoluteString)
print("headers request = ", request.allHTTPHeaderFields.debugDescription)
print("response = ", response)
print("data body = ", String(data: data!, encoding: String.Encoding.utf8.self))
} else {
print("error = ", error)
print(error?.localizedDescription)
}
}).resume()
}
}
URLSessionProxy().doRequest()
$ curl --proxy http://localhost:8888/ https://ip.seeip.org/jsonip
{"ip":"172.217.162.174"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment