问题
I need to load the content of the webview using a proxy. I have this code (Objective-C):
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.connectionProxyDictionary = @{ (NSString *)kCFStreamPropertyHTTPProxyHost: [proxyURL host], (NSString *)kCFStreamPropertyHTTPProxyPort: [proxyURL port] };
The following Xamarin code doesn't work, ConnectionProxyDictionary is set but application doesn't use this settings:
var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration;
configuration.ConnectionProxyDictionary = new NSDictionary("kCFStreamPropertyHTTPProxyHost", proxyURL.Host, "kCFStreamPropertyHTTPProxyPort", proxyURL.port);
How to port above Objective-C code to Xamarin.iOS? Is there another way to achieve the same goal?
回答1:
The reason it does not work is because in Objective-C, the kXX is replaced with an actual reference to a constant, and in C#, you just plugged a string name.
You need to fetch the value of that constant and pass it:
Use this:
using MonoTouch.ObjCRuntime;
...
var keyHost = Dlfcn.GetStringConstant ("kCFStreamPropertyHTTPProxyHost")
var keyPort = Dlfcn.GetStringConstant ("kCFStreamPropertyHTTPProxyPort")
Then use keyHost and keyPort as your parameters in the NSDictionary
回答2:
var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration;
NSObject[] values = new NSObject[]
{
NSObject.FromObject(proxyURL.host), //ProxyHost
NSNumber.FromInt32 (proxyURL.port), //Port
NSNumber.FromInt32 (1), //Enable HTTP proxy
};
NSObject[] keys = new NSObject[]
{
NSObject.FromObject("HTTPProxy"),
NSObject.FromObject("HTTPPort"),
NSObject.FromObject("HTTPEnable")
};
NSDictionary proxyDict = NSDictionary.FromObjectsAndKeys (values, keys);
configuration.ConnectionProxyDictionary = proxyDict;
var session = NSUrlSession.FromConfiguration (configuration);
var task = session.CreateDataTask(NSUrl.FromString("http://google.com"));
task.Resume ();
来源:https://stackoverflow.com/questions/24212216/how-to-add-a-proxy-to-nsurlsession-in-xamarin-ios