0

I am developing a very simple application which accesses a written url. So i am wondering what is the difference between access by nsurlconnection and access by just using browser. cause some sites respond but they don`t send data when i used the nsurlconnection.

- (void)getWikiData:(NSString *)keyword{
NSString* tmpURL = @"http://wikipedia.simpleapi.net/api?keyword=";
NSString* encodedString;
CFStringRef strRef = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)keyword, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]~", kCFStringEncodingUTF8);
encodedString = [NSString stringWithString:(NSString *)strRef];
CFRelease(strRef);
[tmpURL stringByAppendingString:encodedString];
[tmpURL stringByAppendingString:@"&output=html"];
NSURL *url = [NSURL URLWithString:tmpURL];

NSString *userAgent = @"Custom User Agent";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
NSLog(@"Receive Response");

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"Receive Data");
}

Thanks in advance.

1 Answers1

0

The difference is in the user agent string of the resulting application. MobileSafari reports itself as "Safari, iOS like Mac OS X", however, a plain NSURLConnection sends a CFNetwork description, which is not very useful for most sites to do 'browser' (rather 'client') detection, that's why they may refuse to send data to an unrecognized user agent.

  • so if i could set the user agent string of NSURLConnection, I have no problem getting data from any sites? – Mungunbat Enkhbayar Oct 11 '12 at 10:51
  • @MungunbatEnkhbayar Not guaranteed, but you may be closer to the solution. Have a look at `[NSMutableRequest setValue:forHTTPheaderField:]` and the `"User-Agent"` HTTP header value. –  Oct 11 '12 at 11:05
  • I tried below. [NSMutableRequest setValue:forHTTPheaderField:"User-Agent"] But it didn`t work. – Mungunbat Enkhbayar Oct 12 '12 at 05:23
  • @Enkhbayar this doesn't even compile. Grab an Objective-C tutorial, you don't even know the syntax. –  Oct 12 '12 at 05:35
  • i put some codes in my question. So which part doesn`t compile?? – Mungunbat Enkhbayar Oct 12 '12 at 05:55
  • @Mungunbat The code you have written in your comment. You must supply an argument after the first semi-colon. –  Oct 12 '12 at 09:13
  • i set the value. you misunderstood because i didn`t explained fully what i did. Anyway i got what i looking for [@here](http://stackoverflow.com/questions/5695914/nsurlrequest-where-an-app-can-find-the-default-headers-for-http-request) – Mungunbat Enkhbayar Oct 18 '12 at 04:31