阅读784 返回首页    go iPhone_iPad_Mac_apple


单IP多HTTPS域名场景下的解决方案__最佳实践_HTTPDNS-阿里云

1.背景说明

在搭建支持HTTPS的前端代理服务器时候,通常会遇到让人头痛的证书问题。根据HTTPS的工作原理,浏览器在访问一个HTTPS站点时,先与服务器建立SSL连接,建立连接的第一步就是请求服务器的证书。而服务器在发送证书的时候,是不知道浏览器访问的是哪个域名的,所以不能根据不同域名发送不同的证书。

SNI(Server Name Indication)是为了解决一个服务器使用多个域名和证书的SSL/TLS扩展。它的工作原理如下:

  1. 在连接到服务器建立SSL链接之前先发送要访问站点的域名(Hostname)。
  2. 服务器根据这个域名返回一个合适的证书。

目前,大多数操作系统和浏览器都已经很好地支持SNI扩展,OpenSSL 0.9.8也已经内置这一功能。

上述过程中,当客户端使用HTTPDNS解析域名时,请求URL中的host会被替换成HTTPDNS解析出来的IP,导致服务器获取到的域名为解析后的IP,无法找到匹配的证书,只能返回默认的证书或者不返回,所以会出现SSL/TLS握手不成功的错误。

比如当你需要通过HTTPS访问CDN资源时,CDN的站点往往服务了很多的域名,所以需要通过SNI指定具体的域名证书进行通信。

2 解决方案

针对以上问题,可以采用如下方案解决:hook HTTPS访问前SSL连接过程,根据网络请求头部域中的HOST信息,设置SSL连接PeerHost的值,再根据服务器返回的证书执行验证过程。

下面分别列出Android和iOS平台的示例代码。

2.1 Android示例

HTTPDNS Android Demo Github中针对HttpsURLConnection接口,提供了在SNI业务场景下使用HTTPDNS的示例代码。

定制SSLSocketFactory,在createSocket时替换为HTTPDNS的IP,并进行SNI/HostNameVerify配置。

  1. class TlsSniSocketFactory extends SSLSocketFactory {
  2. private final String TAG = TlsSniSocketFactory.class.getSimpleName();
  3. HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
  4. private HttpsURLConnection conn;
  5. public TlsSniSocketFactory(HttpsURLConnection conn) {
  6. this.conn = conn;
  7. }
  8. @Override
  9. public Socket createSocket() throws IOException {
  10. return null;
  11. }
  12. @Override
  13. public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
  14. return null;
  15. }
  16. @Override
  17. public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
  18. return null;
  19. }
  20. @Override
  21. public Socket createSocket(InetAddress host, int port) throws IOException {
  22. return null;
  23. }
  24. @Override
  25. public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
  26. return null;
  27. }
  28. // TLS layer
  29. @Override
  30. public String[] getDefaultCipherSuites() {
  31. return new String[0];
  32. }
  33. @Override
  34. public String[] getSupportedCipherSuites() {
  35. return new String[0];
  36. }
  37. @Override
  38. public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException {
  39. String peerHost = this.conn.getRequestProperty("Host");
  40. if (peerHost == null)
  41. peerHost = host;
  42. Log.i(TAG, "customized createSocket. host: " + peerHost);
  43. InetAddress address = plainSocket.getInetAddress();
  44. if (autoClose) {
  45. // we don't need the plainSocket
  46. plainSocket.close();
  47. }
  48. // create and connect SSL socket, but don't do hostname/certificate verification yet
  49. SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
  50. SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);
  51. // enable TLSv1.1/1.2 if available
  52. ssl.setEnabledProtocols(ssl.getSupportedProtocols());
  53. // set up SNI before the handshake
  54. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  55. Log.i(TAG, "Setting SNI hostname");
  56. sslSocketFactory.setHostname(ssl, peerHost);
  57. } else {
  58. Log.d(TAG, "No documented SNI support on Android <4.2, trying with reflection");
  59. try {
  60. java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
  61. setHostnameMethod.invoke(ssl, peerHost);
  62. } catch (Exception e) {
  63. Log.w(TAG, "SNI not useable", e);
  64. }
  65. }
  66. // verify hostname and certificate
  67. SSLSession session = ssl.getSession();
  68. if (!hostnameVerifier.verify(peerHost, session))
  69. throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost);
  70. Log.i(TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() +
  71. " using " + session.getCipherSuite());
  72. return ssl;
  73. }
  74. }

对于需要设置SNI的站点,通常需要重定向请求,示例中也给出了重定向请求的处理方法。

  1. public void recursiveRequest(String path, String reffer) {
  2. URL url = null;
  3. try {
  4. url = new URL(path);
  5. conn = (HttpsURLConnection) url.openConnection();
  6. // 同步接口获取IP
  7. String ip = httpdns.getIpByHostAsync(url.getHost());
  8. if (ip != null) {
  9. // 通过HTTPDNS获取IP成功,进行URL替换和HOST头设置
  10. Log.d(TAG, "Get IP: " + ip + " for host: " + url.getHost() + " from HTTPDNS successfully!");
  11. String newUrl = path.replaceFirst(url.getHost(), ip);
  12. conn = (HttpsURLConnection) new URL(newUrl).openConnection();
  13. // 设置HTTP请求头Host域
  14. conn.setRequestProperty("Host", url.getHost());
  15. }
  16. conn.setConnectTimeout(30000);
  17. conn.setReadTimeout(30000);
  18. conn.setInstanceFollowRedirects(false);
  19. TlsSniSocketFactory sslSocketFactory = new TlsSniSocketFactory(conn);
  20. conn.setSSLSocketFactory(sslSocketFactory);
  21. conn.setHostnameVerifier(new HostnameVerifier() {
  22. /*
  23. * 关于这个接口的说明,官方有文档描述:
  24. * This is an extended verification option that implementers can provide.
  25. * It is to be used during a handshake if the URL's hostname does not match the
  26. * peer's identification hostname.
  27. *
  28. * 使用HTTPDNS后URL里设置的hostname不是远程的主机名(如:m.taobao.com),与证书颁发的域不匹配,
  29. * Android HttpsURLConnection提供了回调接口让用户来处理这种定制化场景。
  30. * 在确认HTTPDNS返回的源站IP与Session携带的IP信息一致后,您可以在回调方法中将待验证域名替换为原来的真实域名进行验证。
  31. *
  32. */
  33. @Override
  34. public boolean verify(String hostname, SSLSession session) {
  35. String host = conn.getRequestProperty("Host");
  36. if (null == host) {
  37. host = conn.getURL().getHost();
  38. }
  39. return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
  40. }
  41. });
  42. int code = conn.getResponseCode();// Network block
  43. if (needRedirect(code)) {
  44. //临时重定向和永久重定向location的大小写有区分
  45. String location = conn.getHeaderField("Location");
  46. if (location == null) {
  47. location = conn.getHeaderField("location");
  48. }
  49. if (!(location.startsWith("https://") || location
  50. .startsWith("https://"))) {
  51. //某些时候会省略host,只返回后面的path,所以需要补全url
  52. URL originalUrl = new URL(path);
  53. location = originalUrl.getProtocol() + "://"
  54. + originalUrl.getHost() + location;
  55. }
  56. recursiveRequest(location, path);
  57. } else {
  58. // redirect finish.
  59. DataInputStream dis = new DataInputStream(conn.getInputStream());
  60. int len;
  61. byte[] buff = new byte[4096];
  62. StringBuilder response = new StringBuilder();
  63. while ((len = dis.read(buff)) != -1) {
  64. response.append(new String(buff, 0, len));
  65. }
  66. Log.d(TAG, "Response: " + response.toString());
  67. }
  68. } catch (MalformedURLException e) {
  69. Log.w(TAG, "recursiveRequest MalformedURLException");
  70. } catch (IOException e) {
  71. Log.w(TAG, "recursiveRequest IOException");
  72. } catch (Exception e) {
  73. Log.w(TAG, "unknow exception");
  74. } finally {
  75. if (conn != null) {
  76. conn.disconnect();
  77. }
  78. }
  79. }
  80. private boolean needRedirect(int code) {
  81. return code >= 300 && code < 400;
  82. }

2.2 iOS示例

由于iOS系统并没有提供设置SNI的上层接口(NSURLConnection/NSURLSession),因此在HTTPDNS iOS Demo Github中,我们使用NSURLProtocol拦截网络请求,然后使用CFHTTPMessageRef创建NSInputStream实例进行Socket通信,并设置其kCFStreamSSLPeerName的值。

需要注意的是,使用NSURLProtocol拦截NSURLSession发起的POST请求时,HTTPBody为空。解决方案有两个:

  1. 使用NSURLConnection发POST请求。
  2. 先将HTTPBody放入HTTP Header field中,然后在NSURLProtocol中再取出来,Demo中主要演示该方案。

部分代码如下:

在网络请求前注册NSURLProtocol子类,在示例的SNIViewController.m中。

  1. // 注册拦截请求的NSURLProtocol
  2. [NSURLProtocol registerClass:[CFHttpMessageURLProtocol class]];
  3. // 初始化HTTPDNS
  4. HttpDnsService *httpdns = [HttpDnsService sharedInstance];
  5. // 需要设置SNI的URL
  6. NSString *originalUrl = @"your url";
  7. NSURL *url = [NSURL URLWithString:originalUrl];
  8. self.request = [[NSMutableURLRequest alloc] initWithURL:url];
  9. NSString *ip = [httpdns getIpByHostAsync:url.host];
  10. // 通过HTTPDNS获取IP成功,进行URL替换和HOST头设置
  11. if (ip) {
  12. NSLog(@"Get IP from HTTPDNS Successfully!");
  13. NSRange hostFirstRange = [originalUrl rangeOfString:url.host];
  14. if (NSNotFound != hostFirstRange.location) {
  15. NSString *newUrl = [originalUrl stringByReplacingCharactersInRange:hostFirstRange withString:ip];
  16. self.request.URL = [NSURL URLWithString:newUrl];
  17. [_request setValue:url.host forHTTPHeaderField:@"host"];
  18. }
  19. }
  20. // NSURLConnection例子
  21. [[NSURLConnection alloc] initWithRequest:_request delegate:self startImmediately:YES];
  22. // NSURLSession例子
  23. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  24. NSArray *protocolArray = @[ [CFHttpMessageURLProtocol class] ];
  25. configuration.protocolClasses = protocolArray;
  26. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  27. NSURLSessionTask *task = [session dataTaskWithRequest:_request];
  28. [task resume];
  29. // 注*:使用NSURLProtocol拦截NSURLSession发起的POST请求时,HTTPBody为空。
  30. // 解决方案有两个:1. 使用NSURLConnection发POST请求。
  31. // 2. 先将HTTPBody放入HTTP Header field中,然后在NSURLProtocol中再取出来。
  32. // 下面主要演示第二种解决方案
  33. // NSString *postStr = [NSString stringWithFormat:@"param1=%@&param2=%@", @"val1", @"val2"];
  34. // [_request addValue:postStr forHTTPHeaderField:@"originalBody"];
  35. // _request.HTTPMethod = @"POST";
  36. // NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  37. // NSArray *protocolArray = @[ [CFHttpMessageURLProtocol class] ];
  38. // configuration.protocolClasses = protocolArray;
  39. // NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  40. // NSURLSessionTask *task = [session dataTaskWithRequest:_request];
  41. // [task resume];

在NSURLProtocol子类中拦截网络请求,在示例的CFHttpMessageURLProtocol.m中。

  1. + (BOOL)canInitWithRequest:(NSURLRequest *)request {
  2. /* 防止无限循环,因为一个请求在被拦截处理过程中,也会发起一个请求,这样又会走到这里,如果不进行处理,就会造成无限循环 */
  3. if ([NSURLProtocol propertyForKey:protocolKey inRequest:request]) {
  4. return NO;
  5. }
  6. NSString *url = request.URL.absoluteString;
  7. // 如果url以https开头,则进行拦截处理,否则不处理
  8. if ([url hasPrefix:@"https"]) {
  9. return YES;
  10. }
  11. return NO;
  12. }

使用CFHTTPMessageRef创建NSInputStream,并设置kCFStreamSSLPeerName,重新发起请求。

  1. /**
  2. * 开始加载,在该方法中,加载一个请求
  3. */
  4. - (void)startLoading {
  5. NSMutableURLRequest *request = [self.request mutableCopy];
  6. // 表示该请求已经被处理,防止无限循环
  7. [NSURLProtocol setProperty:@(YES) forKey:protocolKey inRequest:request];
  8. curRequest = request;
  9. [self startRequest];
  10. }
  11. /**
  12. * 取消请求
  13. */
  14. - (void)stopLoading {
  15. if (inputStream.streamStatus == NSStreamStatusOpen) {
  16. [inputStream removeFromRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  17. [inputStream setDelegate:nil];
  18. [inputStream close];
  19. }
  20. [self.client URLProtocol:self didFailWithError:[[NSError alloc] initWithDomain:@"stop loading" code:-1 userInfo:nil]];
  21. }
  22. /**
  23. * 使用CFHTTPMessage转发请求
  24. */
  25. - (void)startRequest {
  26. // 原请求的header信息
  27. NSDictionary *headFields = curRequest.allHTTPHeaderFields;
  28. // 添加http post请求所附带的数据
  29. CFStringRef requestBody = CFSTR("");
  30. CFDataRef bodyData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, requestBody, kCFStringEncodingUTF8, 0);
  31. if (curRequest.HTTPBody) {
  32. bodyData = (__bridge_retained CFDataRef) curRequest.HTTPBody;
  33. } else if (headFields[@"originalBody"]) {
  34. // 使用NSURLSession发POST请求时,将原始HTTPBody从header中取出
  35. bodyData = (__bridge_retained CFDataRef) [headFields[@"originalBody"] dataUsingEncoding:NSUTF8StringEncoding];
  36. }
  37. CFStringRef url = (__bridge CFStringRef) [curRequest.URL absoluteString];
  38. CFURLRef requestURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL);
  39. // 原请求所使用的方法,GET或POST
  40. CFStringRef requestMethod = (__bridge_retained CFStringRef) curRequest.HTTPMethod;
  41. // 根据请求的url、方法、版本创建CFHTTPMessageRef对象
  42. CFHTTPMessageRef cfrequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, requestURL, kCFHTTPVersion1_1);
  43. CFHTTPMessageSetBody(cfrequest, bodyData);
  44. // copy原请求的header信息
  45. for (NSString *header in headFields) {
  46. if (![header isEqualToString:@"originalBody"]) {
  47. // 不包含POST请求时存放在header的body信息
  48. CFStringRef requestHeader = (__bridge CFStringRef) header;
  49. CFStringRef requestHeaderValue = (__bridge CFStringRef) [headFields valueForKey:header];
  50. CFHTTPMessageSetHeaderFieldValue(cfrequest, requestHeader, requestHeaderValue);
  51. }
  52. }
  53. // 创建CFHTTPMessage对象的输入流
  54. CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, cfrequest);
  55. inputStream = (__bridge_transfer NSInputStream *) readStream;
  56. // 设置SNI host信息,关键步骤
  57. NSString *host = [curRequest.allHTTPHeaderFields objectForKey:@"host"];
  58. if (!host) {
  59. host = curRequest.URL.host;
  60. }
  61. [inputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL forKey:NSStreamSocketSecurityLevelKey];
  62. NSDictionary *sslProperties = [[NSDictionary alloc] initWithObjectsAndKeys:
  63. host, (__bridge id) kCFStreamSSLPeerName,
  64. nil];
  65. [inputStream setProperty:sslProperties forKey:(__bridge_transfer NSString *) kCFStreamPropertySSLSettings];
  66. [inputStream setDelegate:self];
  67. if (!curRunLoop)
  68. // 保存当前线程的runloop,这对于重定向的请求很关键
  69. curRunLoop = [NSRunLoop currentRunLoop];
  70. // 将请求放入当前runloop的事件队列
  71. [inputStream scheduleInRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  72. [inputStream open];
  73. CFRelease(cfrequest);
  74. CFRelease(requestURL);
  75. CFRelease(url);
  76. cfrequest = NULL;
  77. CFRelease(bodyData);
  78. CFRelease(requestBody);
  79. CFRelease(requestMethod);
  80. }

在NSStream的回调函数中,根据不同的eventCode通知原请求。此处eventCode主要有四种:

  1. NSStreamEventOpenCompleted:连接已打开。
  2. NSStreamEventHasBytesAvailable:响应头部已下载完整,body中字节可读。
  3. NSStreamEventErrorOccurred:连接发生错误。
  4. NSStreamEventEndEncountered:连接结束。
  1. - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
  2. if (eventCode == NSStreamEventHasBytesAvailable) {
  3. CFReadStreamRef readStream = (__bridge_retained CFReadStreamRef) aStream;
  4. CFHTTPMessageRef message = (CFHTTPMessageRef) CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPResponseHeader);
  5. if (CFHTTPMessageIsHeaderComplete(message)) {
  6. // 以防response的header信息不完整
  7. UInt8 buffer[16 * 1024];
  8. UInt8 *buf = NULL;
  9. unsigned long length = 0;
  10. NSInputStream *inputstream = (NSInputStream *) aStream;
  11. NSNumber *alreadyAdded = objc_getAssociatedObject(aStream, kAnchorAlreadyAdded);
  12. if (!alreadyAdded || ![alreadyAdded boolValue]) {
  13. objc_setAssociatedObject(aStream, kAnchorAlreadyAdded, [NSNumber numberWithBool:YES], OBJC_ASSOCIATION_COPY);
  14. // 通知client已收到response,只通知一次
  15. NSDictionary *headDict = (__bridge NSDictionary *) (CFHTTPMessageCopyAllHeaderFields(message));
  16. CFStringRef httpVersion = CFHTTPMessageCopyVersion(message);
  17. // 获取响应头部的状态码
  18. CFIndex myErrCode = CFHTTPMessageGetResponseStatusCode(message);
  19. NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:curRequest.URL statusCode:myErrCode HTTPVersion:(__bridge NSString *) httpVersion headerFields:headDict];
  20. [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
  21. // 验证证书
  22. SecTrustRef trust = (__bridge SecTrustRef) [aStream propertyForKey:(__bridge NSString *) kCFStreamPropertySSLPeerTrust];
  23. SecTrustResultType res = kSecTrustResultInvalid;
  24. NSMutableArray *policies = [NSMutableArray array];
  25. NSString *domain = [[curRequest allHTTPHeaderFields] valueForKey:@"host"];
  26. if (domain) {
  27. [policies addObject:(__bridge_transfer id) SecPolicyCreateSSL(true, (__bridge CFStringRef) domain)];
  28. } else {
  29. [policies addObject:(__bridge_transfer id) SecPolicyCreateBasicX509()];
  30. }
  31. /*
  32. * 绑定校验策略到服务端的证书上
  33. */
  34. SecTrustSetPolicies(trust, (__bridge CFArrayRef) policies);
  35. if (SecTrustEvaluate(trust, &res) != errSecSuccess) {
  36. [aStream removeFromRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  37. [aStream setDelegate:nil];
  38. [aStream close];
  39. [self.client URLProtocol:self didFailWithError:[[NSError alloc] initWithDomain:@"can not evaluate the server trust" code:-1 userInfo:nil]];
  40. }
  41. if (res != kSecTrustResultProceed && res != kSecTrustResultUnspecified) {
  42. /* 证书验证不通过,关闭input stream */
  43. [aStream removeFromRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  44. [aStream setDelegate:nil];
  45. [aStream close];
  46. [self.client URLProtocol:self didFailWithError:[[NSError alloc] initWithDomain:@"fail to evaluate the server trust" code:-1 userInfo:nil]];
  47. } else {
  48. // 证书通过,返回数据
  49. if (![inputstream getBuffer:&buf length:&length]) {
  50. NSInteger amount = [inputstream read:buffer maxLength:sizeof(buffer)];
  51. buf = buffer;
  52. length = amount;
  53. }
  54. NSData *data = [[NSData alloc] initWithBytes:buf length:length];
  55. [self.client URLProtocol:self didLoadData:data];
  56. }
  57. } else {
  58. // 证书已验证过,返回数据
  59. if (![inputstream getBuffer:&buf length:&length]) {
  60. NSInteger amount = [inputstream read:buffer maxLength:sizeof(buffer)];
  61. buf = buffer;
  62. length = amount;
  63. }
  64. NSData *data = [[NSData alloc] initWithBytes:buf length:length];
  65. [self.client URLProtocol:self didLoadData:data];
  66. }
  67. }
  68. } else if (eventCode == NSStreamEventErrorOccurred) {
  69. [aStream removeFromRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  70. [aStream setDelegate:nil];
  71. [aStream close];
  72. // 通知client发生错误了
  73. [self.client URLProtocol:self didFailWithError:[aStream streamError]];
  74. } else if (eventCode == NSStreamEventEndEncountered) {
  75. [self handleResponse];
  76. }
  77. }
  78. - (void)handleResponse {
  79. // 获取响应头部信息
  80. CFReadStreamRef readStream = (__bridge_retained CFReadStreamRef) inputStream;
  81. CFHTTPMessageRef message = (CFHTTPMessageRef) CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPResponseHeader);
  82. if (CFHTTPMessageIsHeaderComplete(message)) {
  83. // 确保response头部信息完整
  84. NSDictionary *headDict = (__bridge NSDictionary *) (CFHTTPMessageCopyAllHeaderFields(message));
  85. // 获取响应头部的状态码
  86. CFIndex myErrCode = CFHTTPMessageGetResponseStatusCode(message);
  87. // 把当前请求关闭
  88. [inputStream removeFromRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  89. [inputStream setDelegate:nil];
  90. [inputStream close];
  91. if (myErrCode >= 200 && myErrCode < 300) {
  92. // 返回码为2xx,直接通知client
  93. [self.client URLProtocolDidFinishLoading:self];
  94. } else if (myErrCode >= 300 && myErrCode < 400) {
  95. // 返回码为3xx,需要重定向请求,继续访问重定向页面
  96. NSString *location = headDict[@"Location"];
  97. NSURL *url = [[NSURL alloc] initWithString:location];
  98. curRequest = [[NSMutableURLRequest alloc] initWithURL:url];
  99. /***********重定向通知client处理或内部处理*************/
  100. // client处理
  101. // NSURLResponse* response = [[NSURLResponse alloc] initWithURL:curRequest.URL MIMEType:headDict[@"Content-Type"] expectedContentLength:[headDict[@"Content-Length"] integerValue] textEncodingName:@"UTF8"];
  102. // [self.client URLProtocol:self wasRedirectedToRequest:curRequest redirectResponse:response];
  103. // 内部处理,将url中的host通过HTTPDNS转换为IP,不能在startLoading线程中进行同步网络请求,会被阻塞
  104. NSString *ip = [[HttpDnsService sharedInstance] getIpByHostAsync:url.host];
  105. if (ip) {
  106. NSLog(@"Get IP from HTTPDNS Successfully!");
  107. NSRange hostFirstRange = [location rangeOfString:url.host];
  108. if (NSNotFound != hostFirstRange.location) {
  109. NSString *newUrl = [location stringByReplacingCharactersInRange:hostFirstRange withString:ip];
  110. curRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:newUrl]];
  111. [curRequest setValue:url.host forHTTPHeaderField:@"host"];
  112. }
  113. }
  114. [self startRequest];
  115. } else {
  116. // 其他情况,直接返回响应信息给client
  117. [self.client URLProtocolDidFinishLoading:self];
  118. }
  119. } else {
  120. // 头部信息不完整,关闭inputstream,通知client
  121. [inputStream removeFromRunLoop:curRunLoop forMode:NSRunLoopCommonModes];
  122. [inputStream setDelegate:nil];
  123. [inputStream close];
  124. [self.client URLProtocolDidFinishLoading:self];
  125. }
  126. }

立即试用HTTPDNS服务,点击此处

最后更新:2016-11-23 16:04:14

  上一篇:go HTTPDNS域名解析场景下如何使用Cookie?__最佳实践_HTTPDNS-阿里云
  下一篇:go 金融云特性__金融云介绍_金融云-阿里云