iOS发送网络请求时设置HTTP代理

需求:iOS发送网络请求时设置HTTP代理

解决方法:利用NSURLSession发送网络请求,并进行相应的设置。

代码例:

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

    sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

    sessionConfig.connectionProxyDictionary =

    @{(NSString *)kCFStreamPropertyHTTPSProxyHost:@"XXX.XXX.XXX.XXX",

      (NSString *)kCFStreamPropertyHTTPSProxyPort:@XXXX,

      (NSString *)kCFNetworkProxiesHTTPEnable:@YES

      };

    NSString* proxyIDPasswd = [NSString stringWithFormat:@"XXXX:XXXXX"];

    NSData* proxyoriginData = [proxyIDPasswd dataUsingEncoding:NSUTF8StringEncoding];

    NSData* proxyencodeData = [GTMBase64 encodeData:proxyoriginData];

    NSString *proxyencodeResult = [[NSString alloc] initWithData:proxyencodeData encoding:NSUTF8StringEncoding];

    NSString *proxyendcode =[NSString stringWithFormat:@"Basic %@",proxyencodeResult];

    [request addValue:proxyendcode forHTTPHeaderField:@"Proxy-Authorization"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:selfdelegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse * response, NSError *error) {

   }];

    [task resume];

你可能感兴趣的:(iOS发送网络请求时设置HTTP代理)