如何通过AFNetworking创建简单的Http请求

时间:2013-10-04 16:53:47

标签: ios afnetworking-2

我仍然在使用ASIHTTPRequest,我正在寻找转移到AFNetworking我也经历了Raywenderlich Crash Course 但它没有使用AFNetworking 2.0

我刚试过以下AFNetworking提到的样本 但它的工作方式却没有。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

NSDictionary *parameters = @{@"UserId": @"24",@"ArticleId":@"0"};

NSLog(@"%@",parameters);



[manager POST:@"http://mysite.com/api/User/showArticleList" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    NSLog(@"JSON: %@", responseObject);


}failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    NSLog(@"Error: %@", error);
}];

显示调试区域:

错误域= NSCocoaErrorDomain代码= 3840
“操作无法完成。(Cocoa error 3840.)”(JSON文本没有以数组或对象开头,并且选项允许未设置片段。)UserInfo = 0xa0ba580 {NSDebugDescription = JSON文本未启动使用数组或对象和选项来允许未设置片段。}

但是当我使用链接提到Raywenderlich速成课程时

 [manager POST:@"http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"JSON: %@", responseObject);
 }failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     NSLog(@"Error: %@", error);
 }];

它为我提供了完美的JSON输出,为什么会这样?

2 个答案:

答案 0 :(得分:7)

我终于找到了解决方案如下 -

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];


  NSDictionary *parameters = @{@"UserId": @"24",@"Name":@"Robin"};

  NSLog(@"%@",parameters);
  parameters = nil;

    // if you want to sent parameters you can use above code 

    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager POST:@"http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {

        NSLog(@"JSON: %@", responseObject);


   }failure:^(AFHTTPRequestOperation *operation, NSError *error)
   {
        NSLog(@"Error: %@", error);
   }];

对于text / Html +,如果它没有提供正确的JSON字符串,您可以将其从字符串中删除并将其转换为数组或字典。

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

        // if you want to sent parameters you can use above code
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
     // header("Content-Type: application/json");
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer];

        manager.responseSerializer = [AFHTTPResponseSerializer serializer];


        [manager GET:@"your url" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"responseObject %@",responseObject);

            NSString *jsonString =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

            NSString *newJsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\'" withString:@""];

/*
NSRange range = [jsonString rangeOfString:@"}" options:NSBackwardsSearch];
jsonString = [jsonString substringToIndex:range.location + 1];
*/
            NSData *data = [newJsonString dataUsingEncoding:NSUTF8StringEncoding];

            NSError *error;
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

            NSLog(@"array %@",array);


            if (!array) {
                NSLog(@"Parsing JSON failed: %@", error);
            }

            /*
             NSData *newJSONData = [newJsonString dataUsingEncoding:NSUTF8StringEncoding];
             NSDictionary* json = [NSJSONSerialization
             JSONObjectWithData:newJSONData
             options:NSJSONReadingMutableContainers
             error:&error];
             NSLog(@"json %@",json);
            */

            NSLog(@"responseObject = %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);


        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            NSLog(@"%@",[error description]);

        }];

在某些情况下,您需要更改响应字典/数组 - 但有时对象的所有片段都不可变。
为此,请按照以下步骤进行。

For Dictionary

 NSError *error;

                NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:responce options:NSJSONWritingPrettyPrinted error:&error];

                responseDictionary = [[NSMutableDictionary alloc]init];

                responseDictionary = [NSJSONSerialization JSONObjectWithData:dataFromDict options:NSJSONReadingMutableContainers error:&error];

适用于数组

NSError *error;

                NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:responce options:NSJSONWritingPrettyPrinted error:&error];

                responseArray = [[NSMutableDictionary alloc]init];

                responseArray = [NSJSONSerialization JSONObjectWithData:dataFromDict options:NSJSONReadingMutableContainers error:&error];

答案 1 :(得分:3)

您似乎在服务器端有一个ASP.NET Web API服务。它默认返回XML。

您有两种选择:

  1. 按照How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

  2. 中的说明更改网络服务的配置
  3. 发送HTTP标头Accept: application/json以及您的请求。