IOS 使用AFNetworking 接收JSON数据(Get and Post)

首先将AFNetworking的库加进来(GitHub搜索),然后如下代码



(GET)

IOS端


AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManagermanager];

mgr.responseSerializer.acceptableContentTypes = [mgr.responseSerializer.acceptableContentTypessetByAddingObject:@"text/html"];//Very Important


[mgr GET:@"test.php"parameters:nilsuccess:^(AFHTTPRequestOperation *operation,id responseObject) {

       NSDictionary *d = responseObject;

        NSString *str = [NSStringstringWithFormat:@"age:%@;\ngender:%@;\nname:%@\n\nresult:%@",d[@"content"][@"age"],d[@"content"][@"gender"],d[@"content"][@"name"],d[@"result"]];

        

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

    {

    

    }];




服务器php脚本


<?php
$content = array(
"userid"=>$_GET['userid'],
"name"=>"rose",
"age"=>"2099",
"gender"=>"female",
"subs"=>array("maths","geo","phy")
);

$result="pass";
$ret = array(
    "result"=>$result,
    "content"=>$content,
    "mask"=>"mask"
);
echo json_encode($ret);


POST


AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManagermanager];

mgr.responseSerializer.acceptableContentTypes = [mgr.responseSerializer.acceptableContentTypessetByAddingObject:@"text/html"];//Very Important

NSDictionary *param = @{@"name:@"jack",@"age":@"33"};

[mgr POST:@"test.php"parameters:param success:^(AFHTTPRequestOperation *operation,id responseObject) {

       NSDictionary *d = responseObject;

        NSString *str = [NSStringstringWithFormat:@"age:%@;\ngender:%@;\nname:%@\n\nresult:%@",d[@"content"][@"age"],d[@"content"][@"gender"],d[@"content"][@"name"],d[@"result"]];

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

    {

      operation.response.statusCode;//404 401之类

    }];


server端略





PS:有的时候需要输入用户名和密码:http://admin:[email protected]/test.php

如果发送的时候需要json格式,则需要设置mgr.requestSerializer = [AFJsonRequestSerializer serializer];




你可能感兴趣的:(IOS 使用AFNetworking 接收JSON数据(Get and Post))