更改NSURLConnection的userAgent

时间:2009-10-07 15:03:34

标签: iphone cocoa cocoa-touch nsurlconnection

嘿我正在使用NSURL Connection来接收数据。

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

是否可以更改用户代理字符串? 现在是:

AppName / AppVersion CFNetwork / 459 Darwin / 10.0.0.d3

2 个答案:

答案 0 :(得分:105)

的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];

夫特:

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
   }
 }

答案 1 :(得分:6)

是的,您需要使用NSMutableURLRequest并为您的用户代理字符串设置自定义标头字段。