1 同步get请求。《get的请求不需要httpbody, 而post请求需要指定 httpbody》
- (IBAction)syncGETAction:(id)sender {
// 同步GET请求
NSString *path =@"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/images_A1/6954/2011100658141857.jpg";
// 1产生一个请求
// 请求地址
NSURL *url = [NSURLURLWithString:path];
// 参数1:请求地址
// 参数2:缓存celue 缓存策略 服务器NSURLRequestUseProtocolCachePolicy
// 参数3:超时时间
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
// 2对请求进行设置
// 请求方式:get / post
request.HTTPMethod =@"GET";
// 3进行网络连接
// 连接服务器的两种方式:同步/异步
// 同步连接
NSURLResponse *response =nil;
NSError *error =nil;
NSData *data = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];/* 如果是图片 就
用imageWithData, 如果是 txt 就用解析*/
// 链接服务器的相关信息
NSLog(@"服务器响应信息:%@", response);
if (error !=nil) {
NSLog(@"错误信息:%@", error);
}
// 通过data产生一个图片
UIImage *image = [UIImageimageWithData:data];
self.imageView.image = image;
// status code: 状态码200 请求成功
}
2 同步post 请求 《需要指定 httpbody》
- (IBAction)syncPOSTAction:(id)sender {
// post请求,同步链接服务器
// 1创建请求
NSString *str =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
// 将字符串转为url
NSURL *url = [NSURLURLWithString:str];
// 建立请求对象
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
// 设定请求方式
request.HTTPMethod =@"POST";
// 设定请求body
NSString *bodyStr =@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
// 将bodyStr转换为NSData类型
NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];
// 设置请求的body(nsdata)
request.HTTPBody = bodyData;
// 2连接服务器
NSURLResponse *response =nil;
NSError *error =nil;
NSData *data = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];
NSLog(@"响应服务器信息:%@", response);
if (error !=nil) {
NSLog(@"错误信息%@", error);
}
// 3将结果转换为字符串
NSString *resultStr = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"post请求的结果:%@", resultStr);
NSMutableDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];
}
3 异步get请求 《NSURLConnectionDataDelegate》
- (IBAction)asyncGETAction:(id)sender {
// get请求方式:异步连接服务器
// 异步:不会卡死界面
// 1生成一个请求
NSURL *url = [NSURLURLWithString:@"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg"];
// 建立请求对象
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
request.HTTPMethod =@"GET";
// 2链接服务器
// 异步链接的方式 协议回调实现异步链接
// 参数1:请求对象
// 参数2:指定一个代理人
[NSURLConnectionconnectionWithRequest:requestdelegate:self];
}
#pragma mark - 异步连接服务器的协议方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%s",__FUNCTION__);
// 收到服务器的响应信息
NSLog(@"收到服务器响应");
// 对data数据进行初始化
self.data = [NSMutableDatadata];
}
- (void)connection:(NSConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%s",__FUNCTION__);
// 收到数据
NSLog(@"接收数据");
[self.dataappendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s",__FUNCTION__);
// 接收数据完毕
NSLog(@"完毕");
UIImage *image = [UIImageimageWithData:self.data];
self.imageView.image = image;
}
4 异步post方法
- (IBAction)asyncPOSTAction:(id)sender {
// post请求方式 :异步连接服务器
// post请求,同步链接服务器
// 1创建请求
NSString *str =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
// 将字符串转为url
NSURL *url = [NSURLURLWithString:str];
// 建立请求对象
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
// 设定请求方式
request.HTTPMethod =@"POST";
// 设定请求body
NSString *bodyStr =@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
// 将bodyStr转换为NSData类型
NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];
// 设置请求的body(nsdata)
request.HTTPBody = bodyData;
// 2异步连接服务器 block回调
// 参数1:请求
// 参数2:操作队列
// 参数3:block回调
[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError) {
NSMutableDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];
NSLog(@"请求结果:%@", dic);
}];
}
//////////////////////////////////////////////////
// 封装请求(方便调用)
//
// NetWorkingHandle.m
// 数据持久化作业
//
// Created by yangtingting on 14-7-28.
// Copyright (c) 2014年 灭神科技. All rights reserved.
//
#import "NetWorkingHandle.h"
@implementation NetWorkingHandle
- (instancetype)init
{
self = [super init];
if (self) {
}
return self;
}
- (void)getDataWithURLString:(NSString *)str completion: (Block)netBlock
{
self.netBlock = netBlock;
// 通过外部传入的参数 创建请求
NSURL *url = [NSURL URLWithString:str];
// 建立请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
// 设定请求方式
request.HTTPMethod = @"GET";
// 建立网络连接 (异步)
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
self.netBlock (result);
}];
}
- (void)getdatawithIDS:(NSString *)ids completion: (Block)netBlock
{
self.netBlock = netBlock;
NSMutableString *string = [NSMutableString stringWithString:@"http://api.douban.com/v2/movie/subject/24879858?apikey=0df993c66c0c636e29ecbb5344252a4a&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&app_name=doubanmovie"];
// 拼接string 网址
[string replaceOccurrencesOfString:@"24879858" withString:ids options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];
// 转码之后的pathstring
[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
- (void)dealloc
{
Block_release(_netBlock);
[super dealloc];
}
@end
在主界面的调用这个类的方法
[net getDataWithURLString:self.stringpic completion:^(id result) {
self.dic = result;
NSLog(@"%@", self.dic);
self.numOf = [[result objectForKey:@"products"] count];
// NSLog(@"%d", self.numOf);
self.arr = [result objectForKey:@"products"];
self.collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 90, 320, 390) collectionViewLayout:layout];
self.collectionview.delegate = self;
self.collectionview.dataSource = self;
[self.view addSubview:self.collectionview];
[self.collectionview release];
[self.collectionview registerClass:[MyCell class] forCellWithReuseIdentifier:@"reuse"];
}];