iOS网络请求GET方式与POST方式

来源:互联网 发布:java关闭线程池 编辑:程序博客网 时间:2024/06/06 18:42

pragma mark 总结:常用的请求方式有两种, 一个是GET, 一个是POST, 他两本质上没有任何区别, 只是post在请求的时候需要添加一个body, 同步和异步: 都使用异步的方式进行加载, 加载过程中还可以操作其他的功能, 不会出现卡死的情况, 从同步演化出异步, 请求分为三步: 1. 创建URL 2. 创建请求request, 3. 建立连接, 完成数据请求, iOS9.0之后, NSURLConnection用的越来越局限, NSURLSession未来更重要

// 同步get请求NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";    // 因为网址里不允许有汉字, 只能有26个字母的大小写, 数字, 和一些指定的符号, 比如&, %, / 等, 所有有中文的网址要先把中文变成相对应的数字编码    // 时间戳    NSString *strURLEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    // 1. 创建一个URL    NSURL *url = [NSURL URLWithString:strURLEncode];    // 2. 发送一个请求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    // 3. 建立一个连接    // 闲来无事的时候看看NSURLSession    // 参数1: 把创建好的请求发送    // 参数2: 返回的响应信息    // 参数3: 错误信息    NSURLResponse *response = nil;    NSError *error = nil;    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];    // 4. 把data进行json解析    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];    NSLog(@"%@", dic);    NSLog(@"*******************%@", response);// post请求需要在请求的过程里, 添加一个body, 添加之后才可以获取数据     NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";    // 1. 创建一个URL    NSURL *url = [NSURL URLWithString:urlStr];    // 2. 创建一个请求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    // 指定请求的方式, 默认是get请求    [request setHTTPMethod:@"post"];    // body的字符串    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";    // body的字符串变成NSData    NSData *dataBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];    // 把bodydata放到request中    [request setHTTPBody:dataBody];    // 3. 建立连接    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];    // 4. json 解析    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];   //    NSLog(@"%@", dic);    //NSLog(@"%@", string);    // 打印summary对应的内容    NSMutableArray *arr = dic[@"news"];    for (NSDictionary *dic in arr) {        NSLog(@"\n");        NSLog(@"\n");        NSLog(@"**********************************************%@", dic[@"summary"]);        NSLog(@"\n");        NSLog(@"\n");    }
0 0
原创粉丝点击