码迷,mamicode.com
首页 > 移动开发 > 详细

NSURLConnection iOS2.0苹果原生请求

时间:2015-09-23 21:09:05      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

get请求1:
 
NSURL*url = [NSURLURLWithString:@"http://127.0.0.1/demo.json"];
   
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //
        if (!connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
          

            //判断服务器返回是否成功
            if (httpResponse.statusCode == 200) {
                //处理服务器返回的数据(解析json)
               
                //把json形式的字符串 解析成对象
               
//                NSJSONReadingMutableContainers = (1UL << 0),  //返回的数组或字典是可变的
//                NSJSONReadingMutableLeaves = (1UL << 1),  //设置json中的字符串是可变的 .但是ios7之后.就不起作用了
               
                //以上两种方式要求.返回的数据必须是json形式的字符串,否则解析会出错
//                NSJSONReadingAllowFragments = (1UL << 2)  //不要求数据是json形式的字符串
               
               
                // 解析json返回的对象,只有两种类型 字典  数组
                NSError *error= nil;
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                //判断解析json的时候是否出错
                if (!error) {
                   
                    NSLog(@"%@",json);
//                    NSLog(@"%@  %@",json[@"message"],[json[@"message"] class]);
                }else{
                    NSLog(@"解析json出错:%@",error);
                }
            }else{
                NSLog(@"服务器内部错误");
            }
        }else{
            NSLog(@"发送请求错误 %@",connectionError);
        }
    }];
}
 
get请求2:(请求头携带参数需要转义)
 
 
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
   
    //当url的字符串,有特殊内容(汉字,空格,url中的特殊符号)
    NSString *name = @"abc&123";
    //只会对汉字 空格进行百分号的转义
    name = [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //对url中的特殊符号进行转义
    name = [self encodeToPercentEscapeString:name];
   
    NSString *pwd = @"abc";
    NSString *str = [NSString stringWithFormat:@"http://127.0.0.1/php/login.php?username=%@&password=%@",name,pwd];
   
    NSURL *url = [NSURL URLWithString:str];
    NSLog(@"%@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //
        if (!connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                //
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                NSLog(@"%@",json);
            }else{
                NSLog(@"服务器内部错误");
            }
        }else{
            NSLog(@"请求错误%@",connectionError);
        }
    }];
}

//进行url编码 (但是不对汉字和空格进行编码)
- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    NSString *outputStr = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)input,NULL,(CFStringRef)@"!*‘();:@&=+ $,/?%#[]",kCFStringEncodingUTF8));
    return outputStr;
}

//url解码
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    return [input
            stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
}
 
post请求:(携带参数请求体传递)
 
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //当url的字符串,有特殊内容(汉字,空格,url中的特殊符号)
  
   
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/php/login.php"];
 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置发送post请求
    request.HTTPMethod = @"post";
   
    //请求体    没有对url中的特殊符号转义
    NSString *name = @"abc123"; //自动对汉字和空格做了百分号转义
   
    NSString *pwd = @"abc";
    NSString *strBody = [NSString stringWithFormat:@"username=%@&password=%@",name,pwd];
    request.HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
   
   
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //
        if (!connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                //
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                NSLog(@"%@",json);
            }else{
                NSLog(@"服务器内部错误");
            }
        }else{
            NSLog(@"请求错误%@",connectionError);
        }
    }];
}

NSURLConnection iOS2.0苹果原生请求

标签:

原文地址:http://www.cnblogs.com/supersr/p/4833355.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!