开发者

Changing the userAgent of NSURLConnection

开发者 https://www.devze.com 2022-12-08 02:26 出处:网络
Hey I am using a NSURL Connection to receive data. [NSURLConnection sendSynchronousRequest: //create request from url

Hey I am using a NSURL Connection to receive data.

[NSURLConnection sendSynchronousRequest:
//create request from url
[NSURLRequest requestWithURL:
  //create url from string
  [NSURL URLWithString:url]
] 
//request parameters
returningResponse:nil error:nil
] 

Is it开发者_如何学Go possible to change the user agent string? right now it is:

AppName/AppVersion CFNetwork/459 Darwin/10.0.0.d3


Obj-C:

NSString* userAgent = @"My Cool User Agent";
NSURL* url = [NSURL URLWithString:@"http://whatsmyuseragent.com/"];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                autorelease];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&response
                                                 error:&error];

Swift:

let userAgent = "My Cool User Agent"
if let url = NSURL(string: "http://whatsmyuseragent.com/") {
   let request = NSMutableURLRequest(URL: url)
   request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
   var response:NSURLResponse? = nil;
   var error:NSError? = nil;
   if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) {
      // do something with your data
   }
 }


Yes, you need to use an NSMutableURLRequest and set a custom header field for your user agent string.

0

精彩评论

暂无评论...
验证码 换一张
取 消