更改NSURLConnection的的userAgent(Changing the userAgen

2019-07-21 06:25发布

嘿,我使用的是NSURL连接接收数据。

[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达尔文/ 10.0.0.d3

Answer 1:

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


Answer 2:

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



文章来源: Changing the userAgent of NSURLConnection