首先将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脚本
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];