本文介绍了更改NSURLConnection的userAgent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 possible to change the user agent string?right now it is:

AppName / AppVersion CFNetwork / 459 Darwin / 10.0.0.d3

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

这篇关于更改NSURLConnection的userAgent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:17