iOS的網路請求

//首先創建一個UIViewController,然後在.m文件中寫入

//簽訂協議

@interface MainViewController ()<NSURLConnectionDataDelegate>

//可變的數據屬性,用來拼接每一小塊數據

@property (nonatomic,retain)NSMutableData *data;

@property (nonatomic,retain)UIImageView *imageView;


@end


@implementation MainViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    

    self.imageView = [[UIImageViewalloc] initWithFrame:CGRectMake(30,64, 280, 200)];

    self.imageView.backgroundColor = [UIColorredColor];

    [self.viewaddSubview:self.imageView];

    [_imageView release];

    

    UIButton *buttonGET = [UIButtonbuttonWithType:UIButtonTypeSystem];

    buttonGET.frame =CGRectMake(50,300, 100, 40);

    buttonGET.backgroundColor = [UIColorcyanColor];

    [buttonGET setTitle:@"GET請求"forState:UIControlStateNormal];

    [buttonGET addTarget:selfaction:@selector(getAction:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:buttonGET];

    

    

    UIButton *buttonPOST = [UIButtonbuttonWithType:UIButtonTypeSystem];

    buttonPOST.frame =CGRectMake(200,300, 100, 40);

    buttonPOST.backgroundColor = [UIColorcyanColor];

    [buttonPOST setTitle:@"POST請求"forState:UIControlStateNormal];

    [buttonPOST addTarget:selfaction:@selector(postAction:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:buttonPOST];

    

    UIButton *buttonSync = [UIButtonbuttonWithType:UIButtonTypeSystem];

    buttonSync.frame =CGRectMake(50,400, 100, 40);

    buttonSync.backgroundColor = [UIColorcyanColor];

    [buttonSync setTitle:@"異步連接(代理)"forState:UIControlStateNormal];

    [buttonSync addTarget:selfaction:@selector(syncAction:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:buttonSync];

    

    UIButton *buttonAsync = [UIButtonbuttonWithType:UIButtonTypeSystem];

    buttonAsync.frame =CGRectMake(200,400, 100, 40);

    buttonAsync.backgroundColor = [UIColorcyanColor];

    [buttonAsync setTitle:@"異步連接(blick)"forState:UIControlStateNormal];

    [buttonAsync addTarget:selfaction:@selector(asynAction:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:buttonAsync];

    

}


- (void)getAction:(UIButton *)button

{

    //get請求

    //1.創建請求

    //地址字符串

    NSString *str =@"添加網址";

    

    //對地址進行編碼處理,對一些特殊字符轉爲utf-8編碼格式

    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

    //通過字符串產生一個url

   NSURL *url = [NSURLURLWithString:str];

    

    //參數1:URL

    //參數2:請求數據的緩存策略

    //參數3:超時時間

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    

    //設置請求方式(GET)

    request.HTTPMethod =@"GET";


    //2.建立連接,連接服務器

    

    //同步連接服務器

    //這個同步的方法可以直接獲取到完整的網絡數據

    

   NSURLResponse *response = nil;

   NSError *error = nil;

    

    //參數1:要發送給服務器的請求

    //參數2:從服務器獲得的響應信息

    //參數3:錯誤信息

   NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:&response error:&error];

    

   NSLog(@"服務器響應信息: %@", response);

   NSLog(@"錯誤信息: %@", error);

    

    

    //3.獲取數據,處理

    

   UIImage *image = [UIImageimageWithData:data];

    

   self.imageView.image = image;

    

}


- (void)postAction:(UIButton *)button

{

    //post請求

    

    //1.創建請求

    

    NSString *str =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    

    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

   NSURL *url = [NSURLURLWithString:str];

    

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    

    //設置請求方式

    

    request.HTTPMethod =@"POST";

    

    //設置post請求body

    

    NSString *bodyStr =@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";

    

    //將一個字符串對象,轉換爲一個NSData對象

    NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];

    

    request.HTTPBody = bodyData;

    

    //2.建立連接,連接服務器

    

   NSURLResponse *response = nil;

   NSError *error = nil;

    

   NSData *resultData = [NSURLConnectionsendSynchronousRequest:request returningResponse:&response error:&error];

    

   NSLog(@"%@", response);

    //3.處理數據

    

    

    

   NSError *errorJSON = nil;

    

    id result = [NSJSONSerializationJSONObjectWithData:resultData options:NSJSONReadingMutableContainerserror:&errorJSON];

    

   NSLog(@"%@", result);

    

    NSString *resultstr = [[NSStringalloc] initWithData:resultDataencoding:NSUTF8StringEncoding];

   NSLog(@"%@", resultstr);

    

}



- (void)syncAction:(UIButton *)button

{

    //異步連接服務器(協議方式連接)

    

    //1.創建請求

    

    NSString *str =@"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";

    

    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

   NSURL *url = [NSURLURLWithString:str];

    

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    

    request.HTTPMethod =@"GET";

    

    //2.連接服務器

    

    [NSURLConnectionconnectionWithRequest:request delegate:self];

    

    

    

 

    

}


//收到服務器的響應信息

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    //每次收到服務器響應信息的時候,對數據進行初始化, 準備拼接

    self.data = [NSMutableDatadata];

   NSLog(@"%@", response);

}


//接收到服務器數據

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    //拼接數據

    [self.dataappendData:data];

    

   NSLog(@"獲取數據");

}


//完成加載

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    //使用數據

    

    id resulet = [NSJSONSerializationJSONObjectWithData:self.dataoptions:NSJSONReadingMutableContainerserror:nil];

    

    

    

   NSLog(@"完成加載");

}





- (void)asynAction:(UIButton *)button

{

    //異步連接(block)

    

    //1.創建請求

    NSString *str =@"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";

    

    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

   NSURL *url = [NSURLURLWithString:str];

    

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

    

    request.HTTPMethod =@"GET";

    

    //2.連接服務器

    

    //參數1:請求

    //參數2:操作隊列,網絡請求完畢, 返回到哪個線程中

    //參數3:處理數據的block

    [NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {

        

       //3.處理數據

       NSError *resultError = nil;

        id result = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:&resultError];

        

       NSLog(@"%@", result);

        

        

    }];

    

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章