网络工具

1.NSURLConnection

2.AFNetworking

3.CFNetwork

//NSURLConnection

//发送同步请求代码

//    1.设置请求路径

NSString*urlStr=[NSStringstringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];

NSURL*url=[NSURLURLWithString:urlStr];

//    2.创建请求对象

NSURLRequest*request=[NSURLRequestrequestWithURL:url];

//    3.发送请求

//发送同步请求,在主线程执行

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

//(一直在等待服务器返回数据,这行代码会卡住,如果服务器没有返回数据,那么在主线程UI会卡住不能继续执行操作)

NSLog(@"--%d--",data.length);

//发送异步请求代码

//    1.设置请求路径

NSString*urlStr=[NSStringstringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];

NSURL*url=[NSURLURLWithString:urlStr];

//    2.创建请求对象

NSURLRequest*request=[NSURLRequestrequestWithURL:url];

//    3.发送请求

//3.1发送同步请求,在主线程执行

//    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

//(一直在等待服务器返回数据,这行代码会卡住,如果服务器没有返回数据,那么在主线程UI会卡住不能继续执行操作)

//3.1发送异步请求

//创建一个队列(默认添加到该队列中的任务异步执行)

//    NSOperationQueue *queue=[[NSOperationQueue alloc]init];

//获取一个主队列

NSOperationQueue*queue=[NSOperationQueuemainQueue];

[NSURLConnectionsendAsynchronousRequest:requestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError){

NSLog(@"--block回调数据--%@---%d",[NSThreadcurrentThread],data.length);

//隐藏HUD,刷新UI的操作一定要放在主线程执行

[MBProgressHUDhideHUD];

//解析data

/*

{"success":"登录成功"}

{"error":"用户名不存在"}

{"error":"密码不正确"}

*/

NSDictionary*dict=[NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableLeaveserror:nil];

NSLog(@"%@",dict);

//判断后,在界面提示登录信息

NSString*error=dict[@"error"];

if(error){

[MBProgressHUDshowError:error];

}else

{

NSString*success=dict[@"success"];

[MBProgressHUDshowSuccess:success];

}

}];

NSLog(@"请求发送完毕");

//使用异步方法发送get请求

//   2.1设置请求路径

NSString*urlStr=[NSStringstringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];

NSURL*url=[NSURLURLWithString:urlStr];

//   2.2创建请求对象

//    NSURLRequest *request=[NSURLRequest requestWithURL:url];//默认就是GET请求

//设置请求超时

NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:url];

request.timeoutInterval=5.0;

//   2.3.发送请求

//使用代理发送异步请求(通常应用于文件下载)

NSURLConnection*conn=[NSURLConnectionconnectionWithRequest:requestdelegate:self];

[conn start];

NSLog(@"已经发出请求---");

}

#pragmamark-NSURLConnectionDataDelegate代理方法

/*

*当接收到服务器的响应(连通了服务器)时会调用

*/

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

{

NSLog(@"接收到服务器的响应");

//初始化数据

self.responseData=[NSMutableDatadata];

}

/*

*当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)

*/

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

{

NSLog(@"接收到服务器的数据");

//拼接数据

[self.responseData appendData:data];

NSLog(@"%d---%@--",self.responseData.length,[NSThreadcurrentThread]);

}

/*

*当服务器的数据加载完毕时就会调用

*/

-(void)connectionDidFinishLoading:(NSURLConnection*)connection

{

NSLog(@"服务器的数据加载完毕");

//隐藏HUD

[MBProgressHUDhideHUD];

//处理服务器返回的所有数据

NSDictionary*dict=[NSJSONSerializationJSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaveserror:nil];

//判断后,在界面提示登录信息

NSString*error=dict[@"error"];

if(error){

[MBProgressHUDshowError:error];

}else

{

NSString*success=dict[@"success"];

[MBProgressHUDshowSuccess:success];

}

NSLog(@"%d---%@--",self.responseData.length,[NSThreadcurrentThread]);

}

/*

*请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)

*/

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

{

//     NSLog(@"请求错误");

//隐藏HUD

[MBProgressHUDhideHUD];

[MBProgressHUDshowError:@"网络繁忙,请稍后重试!"];

}

另外,

NSMutableURLRequest是NSURLRequest的子类,常用方法有

设置请求超时等待时间(超过这个时间就算超时,请求失败)-(void)setTimeoutInterval:(NSTimeInterval)seconds;

设置请求方法(比如GET和POST)-(void)setHTTPMethod:(NSString*)method;

设置请求体-(void)setHTTPBody:(NSData*)data;

设置请求头-(void)setValue:(NSString*)value forHTTPHeaderField:(NSString*)field;

使用NSURLConnection请求HTTPS(SSL)接口

//使用NSURLConnection连接HTTPS站点,需要处理SSL认证,NSURLConnectionDelegate中定义了一些方法来处理认证

//–connection:canAuthenticateAgainstProtectionSpace:

//–connection:didReceiveAuthenticationChallenge:

//一.NSURLConnection中处理SSL

-(BOOL)connection:(NSURLConnection*)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace{

return[protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];

}

//如果接受任何证书

-(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge{

[challenge.sender useCredential:[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust]forAuthenticationChallenge:challenge];

}

//如果使用证书验证

-(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge

{

staticCFArrayRefcerts;

if(!certs){

NSData*certData=[NSDatadataWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"srca"ofType:@"cer"]];

SecCertificateRefrootcert=SecCertificateCreateWithData(kCFAllocatorDefault,CFBridgingRetain(certData));

constvoid*array[1]={rootcert};

certs=CFArrayCreate(NULL,array,1,&kCFTypeArrayCallBacks);

CFRelease(rootcert);// for completeness, really does not matter

}

SecTrustReftrust=[[challenge protectionSpace]serverTrust];

interr;

SecTrustResultTypetrustResult=0;

err=SecTrustSetAnchorCertificates(trust,certs);

if(err==noErr){

err=SecTrustEvaluate(trust,&trustResult);

}

CFRelease(trust);

BOOL trusted=(err==noErr)&&((trustResult==kSecTrustResultProceed)||(trustResult==kSecTrustResultConfirm)||(trustResult==kSecTrustResultUnspecified));

if(trusted){

[challenge.sender useCredential:[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust]forAuthenticationChallenge:challenge];

}else{

[challenge.sender cancelAuthenticationChallenge:challenge];

}

}

AFNetworking:

AFNetworking下载地址:https://github.com/AFNetworking/AFNetworking

AFNetworking框架中处理SSL

使用AFURLConnectionOperation类的下面两个方法,分别将上述代码以block方式传入即可。

–setAuthenticationAgainstProtectionSpaceBlock:

–setAuthenticationChallengeBlock:

你可能感兴趣的:(网络工具)