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

LIA*_*IAL 4 objective-c request ios afnetworking-2

我需要发送普通的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);
                              }];
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

问候,亚历克斯.

Rob*_*Rob 17

你在评论中说,回应使用的建议AFHTTPRequestOperationManager:

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

您可以使用以下方法解决这个问题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);
}];
Run Code Online (Sandbox Code Playgroud)

您还可以使用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];
Run Code Online (Sandbox Code Playgroud)

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