使用AFNetworking或NSURLConnection将HTTP Body作为字符串发送

时间:2015-10-11 13:03:58

标签: ios objective-c iphone json afnetworking

我正在使用POST网络服务,它接受像这样的参数

jsonObj = {
  "id" : 0,
  "platform" : 1,
  "method" : "Home"
}

所以如何在参数中发送它我使用AFNetworking来使用webservice。

我的代码

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager.requestSerializer setValue:ContentType forHTTPHeaderField:@"Content-Type"];


NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"id",[NSNumber numberWithInt:1],@"platform",API_HomeProductList,@"method", nil];
 NSDictionary *param =[NSDictionary dictionaryWithObjectsAndKeys:dic,@"jsonObj", nil];
[manager POST:APIMainURL parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSMutableDictionary *json = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]]; //
    NSLog(@"JSON: %@",json);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}];

当我通过AFNetworking将其转换为Json后看到我的参数时,它变为有效的json

{
  "jsonObj" = {
    "id" : 0,
    "platform" : 1,
    "method" : "Home"
  }
}

但是我得到一些错误导致我的网络服务

jsonObj = {
   "id" : 0,
   "platform" : 1,
   "method" : "Home"
 } 

作为参数

所以请建议我如何发送

jsonObj = {
   "id" : 0,
   "platform" : 1,
   "method" : "Home"
}
参数

中的

1 个答案:

答案 0 :(得分:0)

我觉得你误会了什么。您的网站

jsonObj={
   "id" : 0,
   "platform" : 1,
   "method" : "Home"
 } 

这意味着你需要创建一个json

{
   "id" : 0,
   "platform" : 1,
   "method" : "Home"
 } 

所以,你只需删除1行代码

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager.requestSerializer setValue:ContentType forHTTPHeaderField:@"Content-Type"];


NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"id",[NSNumber numberWithInt:1],@"platform",API_HomeProductList,@"method", nil];
// NSDictionary *param =[NSDictionary dictionaryWithObjectsAndKeys:dic,@"jsonObj", nil]; /// remove this
[manager POST:APIMainURL parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSMutableDictionary *json = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]]; //
    NSLog(@"JSON: %@",json);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}];