如何使用AFNetworking 2设置HTTP请求?

我需要发送普通的HTTP请求(GET)并在text / html中回答。 如何使用AFNetworkin 2发送此响应?

现在我正在尝试使用

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://example.com"]]; [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; 

并且感到沮丧 – 它什么都不做。 在调试时,也没有触发成功或失败子句。

另外我尝试使用GET:参数:成功:失败:方法,但作为回应我看到这个错误:

错误:错误域= AFNetworkingErrorDomain代码= -1016“请求失败:不可接受的内容类型:text / html”

请问,任何人都可以解释我的错误是什么,以及发送请求的正确方法是什么(如果我将以text / html的forms获得响应)?

问候,亚历克斯。

您在评论中说,响应使用AFHTTPRequestOperationManager的建议:

当我使用GET时,我在上面写了这个错误:错误:错误域= AFNetworkingErrorDomain代码= -1016“请求失败:不可接受的内容类型:text / html”

您可以使用AFHTTPResponseSerializer来解决这个AFHTTPResponseSerializer

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; [manager GET:@"https://example.com" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { // do whatever you'd like here; for example, if you want to convert // it to a string and log it, you might do something like: NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; NSLog(@"%@", string); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; 

您也可以使用AFHTTPRequestOperation

 NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init]; networkQueue.maxConcurrentOperationCount = 5; NSURL *url = [NSURL URLWithString:@"https://example.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { // do whatever you'd like here; for example, if you want to convert // it to a string and log it, you might do something like: NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; NSLog(@"%@", string); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error); }]; [networkQueue addOperation:operation]; 

但理想情况下,建议编写返回JSON(或XML)的服务器代码,因为应用程序更容易使用和解析。

 //AFN 2.0 is just support IOS 7,and it's standard use as follow: AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject) }failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); } ];