同步Get请求
//同步get
-(IBAction)syncGet:(id)sender
{
//url 请求的url
NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
// 方式二
//创建请求数据
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];//忽略缓存策略
//创建连接并将返回结果存放到data中
NSHTTPURLResponse *resp = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&error];//发起同步连接,UI会冻结,直到请求的数据完全收到
//打印状态码
NSLog(@"status code : %d",resp.statusCode);
NSString *str = [[NSString alloc]initWithData:data encoding:4];
NSLog(@"response string %@",str);
}
同步Post请求
//同步post
-(IBAction)syncPost:(id)sender
{
//数据要提交到此url
NSURL *url = [NSURL URLWithString:@"http://api.tudou.com/v3/gw?method=item.comment.add"];
//要提交到服务器的数据 服务器将此xml进行解析
NSString *postStr = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>Wylp5DlhDVs<comment>good</comment>";
NSData *postData = [postStr dataUsingEncoding:4 allowLossyConversion:YES];//将数据转换成二进制流
//创建忽略服务器缓存的请求,超时120
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0f];
//设置HTTP的请求方式
[req setHTTPMethod:@"POST"];//注意大写POST
[req setValue:[NSString stringWithFormat:@"%d",[postData length]] forHTTPHeaderField:@"Content-Length"];
[req setValue:@"text/xml" forHTTPHeaderField:@"content-type"];//若提交的数据格式不同,那么此处的写法也是不同的
[req setHTTPBody:postData];
//提交请求后服务器返回相应的数据
NSHTTPURLResponse *resq = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resq error:&error];
NSString *responseStr = [[NSString alloc]initWithData:data encoding:4];
NSLog(@"responseStr = %@",responseStr);
}
异步Get请求
注意:异步Get请求要实现NSURLConnectionDataDelegate代理 异步请求是不会卡UI的
//异步get
-(IBAction)aSyncGet:(id)sender
{
//请求数据的url
NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
//发送异步请求
//方式一
// [NSURLConnection connectionWithRequest:req delegate:self];
/*
//方式二 可以Cancle掉
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self];
[con start];
//方式三
[[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
*/
}
#pragma NSURLConnection Get Delegate
//接收响应 改方法只执行一遍
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%s",__FUNCTION__);
_mutableData = [[NSMutableData alloc]init];
}
//接收数据 执行多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%s",__FUNCTION__);
[_mutableData appendData:data];
}
//数据接收完
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s",__FUNCTION__);
NSString *string = [[NSString alloc]initWithData:_mutableData encoding:4];
NSLog(@"string = %@",string);
}
//执行失败
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%s",__FUNCTION__);
}
异步Post请求
//异步post
-(IBAction)ayncPost:(id)sender
{
//创建url对象
NSURL *url = [NSURL URLWithString:@"http://api.tudou.com/v3/gw?method=item.comment.add"];
//要提交到服务器的数据 服务器将此xml进行解析
NSString *postStr = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>Wylp5DlhDVs<comment>good</comment>";
NSData *postData = [postStr dataUsingEncoding:4 allowLossyConversion:YES];//将数据转换成二进制流
//创建忽略服务器缓存的请求,超时120
NSMutableURLRequest *reqM = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0f];
//设置HTTP的请求方式
[reqM setHTTPMethod:@"POST"];//注意大写POST
[reqM setValue:[NSString stringWithFormat:@"%d",[postData length]] forHTTPHeaderField:@"Content-Length"];
[reqM setValue:@"text/xml" forHTTPHeaderField:@"content-type"];//若提交的数据格式不同,那么此处的写法也是不同的
[reqM setHTTPBody:postData];
[NSURLConnection connectionWithRequest:reqM delegate:self];
}
数据解析
//解析xml数据
NSString *path = [[NSBundle mainBundle]pathForResource:@"abc" ofType:@"xml"];
NSString *xmlContent = [NSString stringWithContentsOfFile:path encoding:4 error:nil];
//初始化一个文档节点
GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithXMLString:xmlContent options:0 error:nil];
GDataXMLElement *root = [doc rootElement];
NSArray *studentElementArray = [root elementsForName:@"student"];//获取根节点下面的子节点
NSLog(@"studentElementArray = %@",studentElementArray);
//方式一 层层解刨
for (GDataXMLElement *e in studentElementArray)
{
NSArray *arr = [e children];
NSLog(@"arr = %@",arr);
for (GDataXMLElement *chid in arr)
{
NSString *str = [chid stringValue];
NSLog(@"str = %@",str);
}
}
//方式二 直接解剖
NSArray *addressArr = [root nodesForXPath:@"//address" error:nil];
GDataXMLElement *addressElement = [addressArr objectAtIndex:0];
NSLog(@"address = %@",addressElement.stringValue);
//解析json数据
NSString *pathJson = [[NSBundle mainBundle]pathForResource:@"abcd" ofType:@"json"];
NSString *jsonContent = [NSString stringWithContentsOfFile:pathJson encoding:4 error:nil];
NSArray *studentArr = [jsonContent JSONValue];
NSLog(@"studentArr = %@",studentArr);