使用NSURLSessionConfiguration可以设置使用代理服务器做请求:

NSString* proxyHost = @"1.2.3.4";
NSNumber* proxyPort = [NSNumber numberWithInt: 10888];

// Create an NSURLSessionConfiguration that uses the proxy
NSDictionary *proxyDict = @{
                            @"HTTPEnable"  : [NSNumber numberWithInt:1],
                            (NSString *)kCFStreamPropertyHTTPProxyHost  : proxyHost,
                            (NSString *)kCFStreamPropertyHTTPProxyPort  : proxyPort,
                            
                            @"HTTPSEnable" : [NSNumber numberWithInt:1],
                            (NSString *)kCFStreamPropertyHTTPSProxyHost : proxyHost,
                            (NSString *)kCFStreamPropertyHTTPSProxyPort : proxyPort,
                            };

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;


其中,还可以设置HTTPAdditionalHeaders,解决请求头的问题:

NSString *userPasswordString = [NSString stringWithFormat:@"%@:%@", user, password];
NSData * userPasswordData = [userPasswordString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential];
NSString *userAgentString = @"AppName/com.example.app (iPhone 5s; iOS 7.0.2; Scale/2.0)";

configuration.HTTPAdditionalHeaders = @{@"Accept": @"application/json",
                                        @"Accept-Language": @"en",
                                        @"Authorization": authString,
                                        @"User-Agent": userAgentString};


Authorization是解决页面需要认证的情况,比如登录TP-link的路由器,提示你需要用户名和密码
而如果代理服务器需要验证,则可以加上一条类似的头信息,key值不一样
把Authorization 改为 Proxy-Authorization 即可

这个情况可以用curl了解到:

引用
curl -v baidu.com -x 1.2.3.4:10888 --proxy-user abc:xyz
* About to connect() to proxy 1.2.3.4 port 10888 (#0)
*   Trying 1.2.3.4... connected
* Connected to 1.2.3.4 (1.2.3.4) port 10888 (#0)
* Proxy auth using Basic with user 'abc'
> GET http://baidu.com HTTP/1.1
> Proxy-Authorization: Basic abc..xyz=
> User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: baidu.com
> Accept: */*
> Proxy-Connection: Keep-Alive
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK


参考页面:
http://www.objc.io/issues/...
http://stackoverflow.com/q...


原创内容如转载请注明:来自 阿权的书房
收藏本文到网摘
周墨白博客 Homepage Email
2015/09/04 10:52
好专业的样子
分页: 1/1 第一页 1 最后页
发表评论
AD
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML 打开UBB 打开表情 隐藏
昵称   密码   游客无需密码
网址   电邮   [注册]
               

验证码 不区分大小写
 

阅读推荐

服务器相关推荐

开发相关推荐

应用软件推荐