Changing the userAgent of NSURLConnection

后端 未结 2 1035
迷失自我
迷失自我 2020-11-27 12:47

Hey I am using a NSURL Connection to receive data.

[NSURLConnection sendSynchronousRequest:
//create request from url
[NSURLRequest requestWithURL:
  //crea         


        
相关标签:
2条回答
  • 2020-11-27 13:39

    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
       }
     }
    
    0 讨论(0)
  • 2020-11-27 13:46

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

    0 讨论(0)
提交回复
热议问题