I need to implement a custom proxy support for my download program, which currently uses NSURLDownload(), which supports System proxy by default.
Could some one help me with sample code, or correct me what I am doing wrong in the following code snippet.
CFStringRef bodyString = CFSTR("");
CFDataRef bodyData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, bodyString, kCFStringEncodingUTF8, 0);
CFStringRef url ="">CFSTR("http://www.xyzzz.com");
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL);
CFStringRef requestMethod = CFSTR("GET");
CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL,
kCFHTTPVersion1_1);
CFHTTPMessageSetBody(myRequest, bodyData);
CFHTTPMessageSetHeaderFieldValue(myRequest, CFSTR("Cache-Control"), CFSTR("no-cache"));
CFHTTPMessageSetHeaderFieldValue(myRequest, CFSTR("User-Agent"), CFSTR("My Test Agent"));
CFReadStreamRef requestStream = CFReadStreamCreateForHTTPRequest(NULL, myRequest);
//Custom Proxy settings to override the system proxy settings:
NSString *proxyHost = @"10.223.1.226";
NSString *proxyPort = @"3128";
NSDictionary *proxyDict = [NSDictionary dictionaryWithObjectsAndKeys: proxyHost, kCFStreamPropertyHTTPProxyHost, proxyPort,kCFStreamPropertyHTTPProxyPort, nil];
CFReadStreamSetProperty(requestStream, kCFStreamPropertyHTTPProxy, proxyDict);
CFReadStreamOpen(requestStream);
NSMutableData* responseBytes = [NSMutableData data];
NSError *error;
CFHTTPMessageRef response;
while (TRUE) {
if (CFReadStreamHasBytesAvailable(requestStream)) {
UInt8 streambuffer[1024];
int readBytes = CFReadStreamRead (requestStream,streambuffer,sizeof(streambuffer));
NSLog(@"Read: %d",readBytes);
[responseBytes appendBytes:streambuffer length:readBytes];
}
if (CFReadStreamGetStatus(requestStream) == kCFStreamStatusError) {
error = (NSError*)CFReadStreamCopyError (requestStream);
if ([error code] == 61) {
// connection refused
NSLog(@"Error occured: %d",[error code]);
}
break;
}
if (CFReadStreamGetStatus(requestStream) == kCFStreamStatusAtEnd) {
NSLog(@"Stream reached end!");
error = nil;
break;
}
}
response = (CFHTTPMessageRef)CFReadStreamCopyProperty(requestStream, kCFStreamPropertyHTTPResponseHeader);
CFHTTPMessageSetBody(response, (CFDataRef)responseBytes);
CFReadStreamClose(requestStream);
CFRelease(requestStream);