无法使用GET方法使用AFNetworking 2.0获得响应

时间:2014-05-20 14:40:43

标签: ios objective-c json afnetworking

我无法使用这种方法获取数据,但是它在使用其他网址时工作,我也在邮递员中进行了测试,我得到了响应。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

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

manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager GET:@"http://192.168.1.156:81/a.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

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

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

}];

错误:

"Request failed: unacceptable content-type: text/html" UserInfo=0x8a6b000 {NSErrorFailingURLKey=http://192.168.1.156:81/a.php, AFNetworkingOperationFailingURLResponseErrorKey= { URL: http://192.168.1.156:81/a.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Type" = "text/html";
    Date = "Tue, 20 May 2014 14:49:20 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = "Apache/2.4.4 (Win64) PHP/5.4.12";
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "PHP/5.4.12";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}

NSArray转换错误:

  

解析JSON失败:错误域= NSCocoaErrorDomain代码= 3840"操作无法完成。 (可可误差3840。)" (字符4677周围的转义序列无效。)UserInfo = 0xa82c130 {NSDebugDescription =字符4677周围的转义序列无效。}

Parse error on line 258:
...     "story_title": "today\'s story",  
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

3 个答案:

答案 0 :(得分:4)

您的错误消息告诉您AFNetworking期待JSON响应(即响应标头的Content-Type应该是application/json,响应的主体应该是实际的JSON)

这里有许多可能性:

  1. 您的服务正在返回JSON正文,但忽略指定Content-Type标头。在PHP代码中,在发送任何数据之前,请指定Content-Type标题:

    header("Content-Type: application/json");
    

    如果您无法修复PHP(这是首选解决方案),您也可以告诉AFNetworking同时接受text/html作为Content-Type。我没有对此进行测试,但以下内容应将text/html添加到默认acceptableContentTypes的{​​{1}}集中:

    AFJSONResponseSerializer
  2. 您的网络服务并非旨在返回JSON。在这种情况下,您应该将manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; 配置为接受非JSON响应,例如:

    manager
  3. 您的Web服务旨在正确返回JSON响应,但遇到了一些程序错误,导致无法正确生成JSON。在这种情况下,临时更改mananger.responseSerializer = [AFHTTPResponseSerializer serializer]; 以接受非JSON响应(如上面的第2点),然后检查响应(当然,假设您已配置了{{1报告错误):

    manager

    如果您看到了JSON,可以使用php.ini将其转换为数组:

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

    显然,您可以将此本地NSJSONSerialization对象保存到您想要的任何类属性或实例变量中。


  4. 您已使用JSON解析错误更新了问题。这是JSON中NSError *error; NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error]; if (!array) { NSLog(@"Parsing JSON failed: %@", error); } 个字符的结果。那是无效的。 (将您的JSON粘贴到http://jsonlint.com中,它将确认这一点。)您的PHP未正确生成JSON。在NSArray之前删除\。只有在JSON中包含双引号时才应使用此反斜杠转义。

    坦率地说,看起来你手动创建了这个JSON。使用PHP函数\会更好,它可以为您完成所有适当的转义,完全避免这些JSON错误。

答案 1 :(得分:0)

- (void)load_home_page_data_withIndex:(NSString *)startindex andTotalRecord:(NSString *)count {

NSDictionary *favParameter;
NSString *URL1;
[MBProgressHUD showHUDAddedTo:[[[UIApplication sharedApplication] delegate] window] animated:YES];

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];

NSString *uId=[defaults valueForKey:@"UserID"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

URL1=[BASE_URL stringByAppendingString:@"home"];
favParameter=@{
               @"user_id":uId,//[defaults valueForKey:@"UserID"
             //  @"no":startindex,
             //  @"total_record":count,
               };

AFHTTPRequestOperation *op = [manager POST:URL1 parameters:favParameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
}
                                   success:^(AFHTTPRequestOperation *operation, id responseObject)

                              {
                                  __weak Home *weakSelf = self;
                                  [weakSelf.tblObj.pullToRefreshView stopAnimating];
                                  [weakSelf.tblObj.infiniteScrollingView stopAnimating];

                                  [MBProgressHUD hideHUDForView:[[[UIApplication sharedApplication] delegate] window] animated:YES];

                                  NSError *jsonParsingError = nil;
                                  NSMutableDictionary *responseDict = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];


                                  [album_id removeAllObjects];
                                  [photo_id removeAllObjects];
                                  [photo_name removeAllObjects];
                                  [likes removeAllObjects];
                                  [user_id removeAllObjects];
                                  [is_like removeAllObjects];
                                  [Owner_id removeAllObjects];
                                  [imagesarr removeAllObjects];
                                  [user_name removeAllObjects];
                                  [arrPhotoDetail removeAllObjects];
                                  [share_name removeAllObjects];
                                  [date_time removeAllObjects];

                                  [_tblObj setContentOffset:CGPointMake(0, 0)];

                                  int count_notification = [[responseDict valueForKey:@"count_notification"] intValue];
                                  int count_friend_notification = [[responseDict valueForKey:@"count_friend_notification"] intValue];

                                  if (count_notification>0)
                                  {
                                      [_lblNotification_count setText:[NSString stringWithFormat:@"%@  ",[responseDict valueForKey:@"count_notification"]]];
                                      [_lblNotification_count setHidden:NO];
                                  }
                                  else
                                  {
                                      [_lblNotification_count setHidden:YES];
                                  }

                                  if (count_friend_notification>0)
                                  {
                                      [_lblFriendReq_count setText:[NSString stringWithFormat:@"%@  ",[responseDict valueForKey:@"count_friend_notification"]]];
                                      [_lblFriendReq_count setHidden:NO];
                                  }
                                  else
                                  {
                                      [_lblFriendReq_count setHidden:YES];
                                  }

                                  NSString *s1=[NSString stringWithFormat:@"%@",[responseDict valueForKey:@"success"]];
                                  //NSString *s2=[NSString stringWithFormat:@"%@",[responseDict valueForKey:@"msg"]];

                                  if ([s1 isEqualToString:@"1"])
                                  {
                                      [_imgNoData setHidden:YES];

                                      NSMutableArray *arrResult=[responseDict objectForKey:@"result"];

                                      for (int i=0; i<[arrResult count]; i++)
                                      {
                                          NSDictionary *ResultDisc=[arrResult objectAtIndex:i];

                                          [album_id addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"album_id"]]];
                                          [user_name addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"user_name"]]];
                                          [share_name addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"title"]]];
                                          [photo_name addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"user_image"]]];
                                          [likes addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"total_likes"]]];
                                          [is_like addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"is_like"]]];
                                          [arrPhotoDetail addObject:[ResultDisc valueForKey:@"images"]];
                                          [date_time addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"datetime1"]]];

                                          //images
                                          NSArray *arrAns = [ResultDisc valueForKey:@"images"];
                                          NSMutableArray *arr = [[NSMutableArray alloc]init];
                                          //imagesarr
                                          for (int i=0; i<arrAns.count; i++)
                                          {
                                              [arr addObject:[[arrAns objectAtIndex:i] valueForKey:@"photo_title"]];
                                              [Owner_id addObject:[NSString stringWithFormat:@"%@",[arrAns valueForKey:@"owner_id"]]];
                                              [photo_id addObject:[NSString stringWithFormat:@"%@",[arrAns valueForKey:@"photo_id"]]];
                                          }
                                          [imagesarr addObject:arr];
                                          if([ResultDisc objectForKey:@"reviews"] != nil && [[ResultDisc objectForKey:@"reviews"] count] > 0) {
                                              [review addObject:[[ResultDisc objectForKey:@"reviews"] objectAtIndex:0]];
                                          }
                                          else {
                                              [review addObject:@""];
                                          }
                                      }
                                  }
                                  else
                                  {
                                      [_imgNoData setHidden:NO];
                                  }
                                  [_tblObj reloadData];

                              }
                                   failure:^(AFHTTPRequestOperation *operation, NSError *error)
                              {
                                  __weak Home *weakSelf = self;
                                  [weakSelf.tblObj.pullToRefreshView stopAnimating];
                                  [weakSelf.tblObj.infiniteScrollingView stopAnimating];

                                  [MBProgressHUD hideHUDForView:[[[UIApplication sharedApplication] delegate] window] animated:YES];
                                  [Utilities displayAlertWithTitle:@"Network Error" andMessage:@"" forView:self];
                              }];
[op start];

}

答案 2 :(得分:0)

尝试延迟加载:

[cell.Profile_btn setBackgroundImageForState:UIControlStateNormal 
                  withURL:[NSURL URLWithString: [
                      NSString stringWithFormat:@"http://downloadwhatsbest.com/assets/front/users/thumb/%@",
                          [photo_name objectAtIndex:indexPath.row]
                      ]
                  ]
                  placeholderImage:[UIImage imageNamed:@"USER_INVITE"]];

我将其格式化以便更好地阅读。删除空格。