使用OC进行实现GET和POST请求

来源:互联网 发布:edius视频软件 编辑:程序博客网 时间:2024/05/21 06:41
////  ViewController.m//  OC-13_02////  Created by Ibokan on 15/12/28.//  Copyright © 2015年 ibokan. All rights reserved.//#import "ViewController.h"#import "WeiboModel.h"@interface ViewController ()<NSURLConnectionDataDelegate>{    NSMutableData *mData;    NSURLConnection *connentGet;    NSMutableData *mPostData;    NSURLConnection *connetionPost;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];            }//同步post- (IBAction)synPost:(id)sender {    NSString *urlString = @"https://api.weibo.com/2/statuses/update.json";    //编码    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];    //转成NSURL    NSURL *url = [NSURL URLWithString:urlString];    //在OC中使用NSMutableURLRequest进行post请求    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];        NSString*bodyString = @"status=你好&access_token=2.00IujYFE8Evp8C32ce30bc02uNGpHE";        NSData *data = [bodyString dataUsingEncoding:4];    //设置方法体    [mRequest setHTTPMethod:@"post"];    [mRequest setHTTPBody:data];        NSData *resultData = [NSURLConnection sendSynchronousRequest:mRequest returningResponse:nil error:nil];    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingAllowFragments error:nil];    NSLog(@"dictionary = %@",dictionary);    }//异步post- (IBAction)asynPost:(id)sender {        NSString*urlString = @"https://api.weibo.com/2/statuses/update.json";    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];    NSURL *url = [NSURL URLWithString:urlString];        //在OC中使用NSMutableURLRequest发送post请求    NSMutableURLRequest *mAsynRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];        NSString *bodyString = @"status=恭喜恭喜&access_token=2.00IujYFE8Evp8C32ce30bc02uNGpHE";    NSData *data = [bodyString dataUsingEncoding:4];        //设置方法体    [mAsynRequest setHTTPMethod:@"post"];    [mAsynRequest setHTTPBody:data];        //连接    connetionPost = [NSURLConnection connectionWithRequest:mAsynRequest delegate:self];                }//同步- (IBAction)synchronousGet:(id)sender {        //拿到urlString    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00IujYFE8Evp8C32ce30bc02uNGpHE";        //编码    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];        //转换成NSURL    NSURL *url = [NSURL URLWithString:urlString];        /*创建并返回一个URL请求,指向一个指定的URL,采用对应的缓存策略 和 超时相应时长(默认时长60秒)     NSURLRequestCachePolicy 缓存策略     :【       NSURLRequestUseProtocolCachePolicy:默认的缓存策略,如果缓存不存在,直接从服务端获取,如果缓存存在,会根据response中的Cache-Control字段判断下一步操作,如:Cache-Control字段为must-revalidata,则询问服务端该数据时否有更新,无更新的话直接返回给用户缓存数据,若已更新,则请求服务端。            NSURLRequestReloadIgnoringLocalCacheData:忽略本地缓存数据,直接请求服务端            NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地缓存,代理服务器以及其他中介,直接请求源服务器            NSURLRequestReloadIgnoringCacheData:= NSURLRequestReloadIgnoringLocalCacheData            NSURLRequestReturnCacheDataElseLoad:有缓存就用它,不管其有效性(忽略Cache-Control字段),无则请求服务器            NSURLRequestReturnCacheDataDontLoad:死活加载本地缓存,没有就失败(确定当前无网络时使用)            NSURLRequestReloadRevalidatingCacheData:缓存数据必须得到服务端确认有效才使用      】     */    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];    //服务器返回的网络请求的一些参数    NSURLResponse *httpUrlResponse;        NSError *error ;        //在OC中使用NSURLConnection类,和服务器连接,这里是同步连接    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&httpUrlResponse error:&error];        //Json数据格式解析,利用系统提供的API进行Jison数据解析    /*     <#(NSJSONReadingOptions)#>          NSJSONReadingMutableContainers :返回的时可变容器     NSJSONReadingMutableLeaves :返回的Json对象中字符串的值为NSMutableString     NSJSONReadingAllowFragments :允许Json字符串最外层既不是NSArray也不是NSDictionary,但是必须是有效的Json Fragment     */    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];//    NSLog(@"dictionary = %@",dictionary);//    //    NSArray *array =  dictionary[@"statuses"];//    NSLog(@"array = %@",[array[0]valueForKey:@"text"]);    WeiboModel *weibo = [[WeiboModel alloc]initWithDictionary:dictionary];       // NSLog(@"%@",weibo.statuses[0]);    NSLog(@"%@",[weibo.statuses[0] objectForKey:@"text"]);    self.textView.text = [weibo.statuses[0] objectForKey:@"text"];    }//异步- (IBAction)asynchronousGet:(id)sender {        //拿到urlString    NSString *urlString = @"https://api.weibo.com/2/statuses/friends_timeline/ids.json?access_token=2.00IujYFE8Evp8C32ce30bc02uNGpHE";        //编码    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];        //转换成NSURL    NSURL *url = [NSURL URLWithString:urlString];        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];    //异步请求有两种方式;一种是使用代理,一种是使用block    //使用代理方式进行异步请求    connentGet = [NSURLConnection connectionWithRequest:request delegate:self];        //使用block    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];        WeiboModel *weibo = [[WeiboModel alloc]initWithDictionary:dictionary];                //NSLog(@"%@",[weibo.statuses[0] objectForKey:@"text"]);                dispatch_async(dispatch_get_main_queue(), ^{            self.textView.text = [weibo.statuses[0] objectForKey:@"text"];        });//更新UI        }];            }#pragma mark~~~~~~~~~~~~协议~~~~~~~~~~~~~//服务器开始响应,准备想客户发送数据- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    NSLog(@"服务器开始响应,准备想客户发送数据");    if (connection == connentGet) {        mData = [NSMutableData data];    }    if (connection == connetionPost) {        mPostData = [NSMutableData data];    }}//从服务器接收数据,并且此方法会执行很多次- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    NSLog(@"从服务器接收数据,并且此方法会执行很多次");    if (connection == connentGet) {        [mData appendData:data];    }    if (connection == connetionPost) {       [mPostData appendData:data];    }        }//接收数据完成- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"接收数据完成");    if (connection == connentGet) {        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:mData options:NSJSONReadingAllowFragments error:nil];//使用系统的解析工具解析mData                WeiboModel *weibo = [[WeiboModel alloc]initWithDictionary:dictionary];                //[self.textView performSelectorOnMainThread:@selector(setText:) withObject:[weibo.statuses[0] objectForKey:@"text"] waitUntilDone:NO];        self.textView.text = [weibo.statuses[0] objectForKey:@"text"];        /*         更新UI最好在主线程中更新,原因如下:         1.在子线程中是不能进行UI更新的,二可以更新的结果只有一个幻想:因为子线程代码执行完毕,又自动进入到主线程,执行了主线程中的UI更新的函数栈,这中间的时间非常短,就让大家误以为子线程可以更新UI,如果子线程一直在运行,则子线程中的UI更新的函数栈,主线程无法获知,既无法更新         2.之哟普极少数的UI能,因为开辟线程时会获取当前环境,如点击某个按钮,这个按钮响应的方式是开辟一个子线程,在子线程中对该按钮进行UI更新是能及时的,如换标题,换背景音乐,但是这没有任何意义         */    }    if (connection == connetionPost) {        [NSJSONSerialization JSONObjectWithData:mPostData options:NSJSONReadingAllowFragments error:nil];    }}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


建立model

////  WeiboModel.h//  OC-13_02////  Created by Ibokan on 15/12/28.//  Copyright © 2015年 ibokan. All rights reserved.//#import <Foundation/Foundation.h>@interface WeiboModel : NSObject@property (nonatomic,strong)NSArray *statuses;@property (nonatomic,strong)NSArray *advertises;@property (nonatomic,strong)NSArray *ad;@property (nonatomic,strong)NSNumber *hasvisible;@property (nonatomic,strong)NSNumber *previous_cursor;@property (nonatomic,strong)NSNumber *next_cursor;@property (nonatomic,strong)NSNumber *total_number;@property (nonatomic,strong)NSNumber *interval;@property (nonatomic,strong)NSNumber *uve_blank;@property (nonatomic,strong)NSNumber *since_id;@property (nonatomic,strong)NSNumber *max_id;@property (nonatomic,strong)NSNumber *has_unread;-(id)initWithDictionary:(NSDictionary *)dictionary;@end

////  WeiboModel.m//  OC-13_02////  Created by Ibokan on 15/12/28.//  Copyright © 2015年 ibokan. All rights reserved.//#import "WeiboModel.h"@implementation WeiboModel-(id)initWithDictionary:(NSDictionary *)dictionary{    if (self == [super init]) {        [self setValuesForKeysWithDictionary:dictionary];    }    return self;}@end

建立Main.storyboard

建立Main.storyboard


配置网络协议从HTTPS-》HTTP

在 info右击=>openAs=>SourceCode 第24行加入



0 0