iOS网络编程

来源:互联网 发布:多益网络股价 编辑:程序博客网 时间:2024/06/07 23:22

#import <UIKit/UIKit.h>

@interface RootViewController :UIViewController<NSURLConnectionDataDelegate>

{

   UIImageView *imageV;

   //创建可变data接收下载的数据

   NSMutableData *myData;

}

@end

// ***********************************************************//

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {

   [superviewDidLoad];

   self.navigationItem.title =@"网络编程";

   /*

   从服务器拿数据,可以用get也可以用postget请求完全透明,暴露在网址中,而post请求,有body体,我们可以将需要保密的东西放在body里面

    例如从服务器下载一首歌  

    get:www.getmusic-name = @"lalala"....

    post:www.getmusic...body = (里面东西看不见)

   */

   /*

   向服务器发送数据

    get  要发送的内容,还是暴露在网址里面(其实就只能发字符串)并且大小要求小于255字节

    post 要发送的内容放在body里面看不见,有保密特性,大小可以超过1G

   */

   imageV = [[UIImageViewalloc] initWithFrame:CGRectMake(40,120, self.view.frame.size.width - 80, 400)];

   imageV.backgroundColor = [UIColorwhiteColor];

   [self.viewaddSubview:imageV];


   UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

   button.frame =CGRectMake(10,50, 80,40);

   [button setTitle:@"同步GET"forState:UIControlStateNormal];

   button.backgroundColor = [UIColorblackColor];

   button.showsTouchWhenHighlighted =YES;

   button.titleLabel.font = [UIFontsystemFontOfSize:16];

   [self.viewaddSubview:button];

   [button addTarget:selfaction:@selector(tongBuGet)forControlEvents:UIControlEventTouchUpInside];


   UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];

   button2.frame =CGRectMake(100,50, 80,40);

   [button2 setTitle:@"同步POST"forState:UIControlStateNormal];

   button2.backgroundColor = [UIColorblackColor];

   button2.showsTouchWhenHighlighted =YES;

   button2.titleLabel.font = [UIFontsystemFontOfSize:16];

   [self.viewaddSubview:button2];

   [button2 addTarget:selfaction:@selector(tongBuPost)forControlEvents:UIControlEventTouchUpInside];

   

   UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];

   button3.frame =CGRectMake(190,50, 80,40);

   [button3 setTitle:@"异步block"forState:UIControlStateNormal];

   button3.backgroundColor = [UIColorblackColor];

   button3.showsTouchWhenHighlighted =YES;

   button3.titleLabel.font = [UIFontsystemFontOfSize:16];

   [self.viewaddSubview:button3];

   [button3 addTarget:selfaction:@selector(yiBuBlock)forControlEvents:UIControlEventTouchUpInside];

   

   UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];

   button4.frame =CGRectMake(280,50, 80,40);

   [button4 setTitle:@"异步代理"forState:UIControlStateNormal];

   button4.backgroundColor = [UIColorblackColor];

   button4.showsTouchWhenHighlighted =YES;

   button4.titleLabel.font = [UIFontsystemFontOfSize:16];

   [self.viewaddSubview:button4];

   [button4 addTarget:selfaction:@selector(yiBuDelegate)forControlEvents:UIControlEventTouchUpInside]; 

}

//异步代理 借助代理方法下载图片

- (void)yiBuDelegate

{

   NSString *str =@"http://imgsrc.baidu.com/forum/w%3D580/sign=fdd4c315b9014a90813e46b599763971/b962d4bf6c81800afa1bf5a9b13533fa838b4751.jpg";

   NSURL *url = [NSURLURLWithString: str];

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

   request.HTTPMethod =@"GET";

   //借助代理

   [NSURLConnectionconnectionWithRequest: request delegate: self];

}

#pragma mark -- NSURLConnection的代理方法

//1、收到服务器响应信息

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

{

   //初始化data

   myData = [NSMutableDatadata];

}

//2、收到数据

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

{

   //收到的数据加到可变data里面

   [myDataappendData: data];

}

//3、下载失败

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

   NSLog(@"%@",error);

}

//4、下载完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

   UIImage *image = [UIImageimageWithData: myData];

   imageV.image = image;

}

//异步block下载图片

- (void)yiBuBlock

{

   NSString *str =@"http://b.hiphotos.baidu.com/image/h%3D360/sign=ba4fae7036d12f2ed105a8667fc3d5ff/94cad1c8a786c917be9d9d9ec93d70cf3ac757ff.jpg";

   NSURL *url = [NSURLURLWithString: str];

   //创建请求

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

   //设置请求方式

   request.HTTPMethod =@"GET";

   //发送请求当程序执行到这一行时,并不会停止,继续执行下面的代码,当下载结束之后,再回来执行block内部代码,是异步请求方式,不会造成程序假死现象 

   //  NSOperationQueue mainQueue 主线程

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

   // 下载结束走这里

    UIImage *image = [UIImageimageWithData: data];

    imageV.image = image;

   }];

}

//同步下载网易新闻

- (void)tongBuPost

{

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

   NSURL *url = [NSURLURLWithString: str];

   //创建请求

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

   //设置请求方式

   request.HTTPMethod =@"POST";

   //设置body

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

   //将字符串转成NSData

   NSData *data = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];//编码格式

   request.HTTPBody = data;

   //发送请求

   NSURLResponse *response =nil;

   NSError *error =nil;

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

   //data转成字符串打印

   NSString *resultStr = [[NSStringalloc] initWithData: dataResultencoding:NSUTF8StringEncoding];

   NSLog(@"%@",resultStr);

}

//同步下载图片

- (void)tongBuGet

{

   NSString *str =@"http://h.hiphotos.baidu.com/image/h%3D360/sign=f44985e6cf80653864eaa215a7dca115/8cb1cb1349540923ba0e63d69758d109b3de4936.jpg";

   //将字符串转成网址

   NSURL *url = [NSURLURLWithString: str];

   //创建一个请求 参数1:网址 参数2:缓存策略 参数3:超时时间

   NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval: 60];//超过60秒请求失败  post 3.0 始终是240

   //设置请求方式(默认就是GET,要大写)

   request.HTTPMethod =@"GET";

   //发送请求 参数1:请求  参数2:服务器的相应信息  参数3:错误信息

   //创建相应信息和错误信息

   NSURLResponse *response =nil;

   NSError *error =nil;

   //同步请求 当程序执行的这一行  会出现假死状态,直到下载结束之后才会继续往下执行下面的代码

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

   UIImage *image = [UIImageimageWithData: data];

   imageV.image = image;  

}

- (void)didReceiveMemoryWarning {

   [superdidReceiveMemoryWarning];

}

@end



0 0
原创粉丝点击