iOS 网络请求


网络请求常用类

NSURL  ---请求地址

NSURLRequest ---GET请求使用

NSMutableURLRequest ---POST请求使用

NSURLConnection ---连接 发送NSURLRequest对象中的数据并收集来自服务器的响应


代理方法 不建议用

NSURLConnectionDataDelegate 

//服务器开始返回数据

-(void)connection:didReceiveResponse:

//收到服务器返回的数据,本方法会被调用多次

-(void)connection:didReceiveData:

//数据接收完毕,做数据的最后处理

-(void)connectionDidFinishLoading:

//网络连接错误

-(void)connection:didFailWithError:

//发送数据给服务器,POST请求使用次方法

-(void)connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:


使用post 同步发送请求

-(void)login
{
	NSString * urlString = [NSString stringWithFormat:@"http://192.168.1.1/login.php"];
	NSURL * url = [NSURL URLWithString:urlString];
	NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
	//第一个参数url 缓存策略 超时时长
	NSURLRequest * request1 = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
	//网络访问超时时间
	[request setTimeoutInterval:2.0f];
	//默认是get
	[request setHTTPMethod:@"POST"];
	NSString * bodyStr = [NSString stringWithFormat:@"username=%@&password=%@",userName,password];
	NSData * body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
	[request setHTTPBody:body];	
	//同步请求
	NSURLResponse * response = nil;
	NSError * error = nil;
	NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	/*
	1、接受到数据,表示工作正常
	2、没有接受到数据,但是error为nil 表示接收到空数据
	3、error不为空 表示请求出错
	*/
	if(data != nil)
	{
		NSString * str = [[NSString alloc]initWithData:data encoding	:NSUTF8StringEncoding];
		NSLog(@"%@",str);
	}else if(data ==nil &&error ==nil)
	{
		NSLog(@"接收到空数据");
	}else
	{
		NSLog(@"%@",error.localizedDescription);
	}
}


异步请求

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse * response, NSData* data,NSError *error)

{

if(data != nil)

{

NSString * str = [[NSString alloc]initWithData:data encoding :NSUTF8StringEncoding];

NSLog(@"%@",str);

}else if(data ==nil &&error ==nil)

{

NSLog(@"接收到空数据");

}else

{

NSLog(@"%@",error.localizedDescription);

}



}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值