在iOS中, 有一种网络请求方式为GET, 分为同步GET和异步GET:
1 同步GET实例代码
创建一个继承与NSObject的SyncGetConnect类, 在其.m中实现以下方法
- (NSData *)startConcent
{
//准备网址,网址就是一个字符串
NSString *urlStr =@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php";
//如果网址中有汉字或空格, 需要用以下方法进行转换
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 构建网络URL对象,NSURL
NSURL *url = [NSURLURLWithString:urlStr];
//将网址进行封装,包括请求方式
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
//告诉接下来的网络连接,这个网络请求是什么样的网络请求形式
[requestsetHTTPMethod:@"GET"];
// 创建同步链接
// 连接服务器,同步
NSURLResponse *responce =nil;// 服务器返回信息
NSError *error =nil;
NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:&responce error:&error];
// 把data转换为可读的文本,用于分析
NSString *str = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
[strrelease];
return data;
}
SyncGetConnect *connect = [[SyncGetConnectalloc] init];
NSData *data = [connect startConcent];
// JSON解析
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:nil];
NSArray *array = [dic objectForKey:@"events"];
[connectrelease]
3 异步GET实例代码:- (void)startParser1:(NSString *)urlStr
{
NSURL *url = [NSURLURLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
[requestsetHTTPMethod:@"GET"];
//异步网络请求,通过协议来完成
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
// 获得服务器响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response
{
}
// 接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//由于网络原因,接收数据的方法会走多次,因此需要将每次得到的数据拼接起来
[_receiveDataappendData:data];
}
// 接收数据完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
NSString *str = [NSStringstringWithFormat:@"http://hunliji.com/productRecommend.json?count=%d",6];
AsyncGetConnect *connect = [[AsyncGetConnectalloc] init];
[connectstartParser1:str];
NSLog(@"%@", str);
[connectrelease];