How to add a proxy to NSURLSession in Xamarin.iOS?

馋奶兔 提交于 2020-01-06 21:47:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!