1.NSURLConnection
2.AFNetworking
3.CFNetwork
//NSURLConnection
//發(fā)送同步請(qǐng)求代碼
// ? ?1.設(shè)置請(qǐng)求路徑
NSString*urlStr=[NSStringstringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL*url=[NSURLURLWithString:urlStr];
// ? ?2.創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest*request=[NSURLRequestrequestWithURL:url];
// ? ?3.發(fā)送請(qǐng)求
//發(fā)送同步請(qǐng)求,在主線(xiàn)程執(zhí)行
NSData*data=[NSURLConnectionsendSynchronousRequest:request returningResponse:nil error:nil];
//(一直在等待服務(wù)器返回?cái)?shù)據(jù),這行代碼會(huì)卡住荆秦,如果服務(wù)器沒(méi)有返回?cái)?shù)據(jù)待错,那么在主線(xiàn)程UI會(huì)卡住不能繼續(xù)執(zhí)行操作)
NSLog(@"--%d--",data.length);
//發(fā)送異步請(qǐng)求代碼
// ? ?1.設(shè)置請(qǐng)求路徑
NSString*urlStr=[NSStringstringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL*url=[NSURLURLWithString:urlStr];
// ? ?2.創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest*request=[NSURLRequestrequestWithURL:url];
// ? ?3.發(fā)送請(qǐng)求
//3.1發(fā)送同步請(qǐng)求凡蜻,在主線(xiàn)程執(zhí)行
// ? ?NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//(一直在等待服務(wù)器返回?cái)?shù)據(jù)般此,這行代碼會(huì)卡住,如果服務(wù)器沒(méi)有返回?cái)?shù)據(jù)饭弓,那么在主線(xiàn)程UI會(huì)卡住不能繼續(xù)執(zhí)行操作)
//3.1發(fā)送異步請(qǐng)求
//創(chuàng)建一個(gè)隊(duì)列(默認(rèn)添加到該隊(duì)列中的任務(wù)異步執(zhí)行)
// ? ?NSOperationQueue *queue=[[NSOperationQueue alloc]init];
//獲取一個(gè)主隊(duì)列
NSOperationQueue*queue=[NSOperationQueuemainQueue];
[NSURLConnectionsendAsynchronousRequest:requestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError){
NSLog(@"--block回調(diào)數(shù)據(jù)--%@---%d",[NSThreadcurrentThread],data.length);
//隱藏HUD嘱蛋,刷新UI的操作一定要放在主線(xiàn)程執(zhí)行
[MBProgressHUDhideHUD];
//解析data
/*
{"success":"登錄成功"}
{"error":"用戶(hù)名不存在"}
{"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(@"請(qǐng)求發(fā)送完畢");
//使用異步方法發(fā)送get請(qǐng)求
// ? 2.1設(shè)置請(qǐng)求路徑
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創(chuàng)建請(qǐng)求對(duì)象
// ? ?NSURLRequest *request=[NSURLRequest requestWithURL:url];//默認(rèn)就是GET請(qǐng)求
//設(shè)置請(qǐng)求超時(shí)
NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:url];
request.timeoutInterval=5.0;
// ? 2.3.發(fā)送請(qǐng)求
//使用代理發(fā)送異步請(qǐng)求(通常應(yīng)用于文件下載)
NSURLConnection*conn=[NSURLConnectionconnectionWithRequest:requestdelegate:self];
[conn start];
NSLog(@"已經(jīng)發(fā)出請(qǐng)求---");
}
#pragmamark-NSURLConnectionDataDelegate代理方法
/*
*當(dāng)接收到服務(wù)器的響應(yīng)(連通了服務(wù)器)時(shí)會(huì)調(diào)用
*/
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
NSLog(@"接收到服務(wù)器的響應(yīng)");
//初始化數(shù)據(jù)
self.responseData=[NSMutableDatadata];
}
/*
*當(dāng)接收到服務(wù)器的數(shù)據(jù)時(shí)會(huì)調(diào)用(可能會(huì)被調(diào)用多次,每次只傳遞部分?jǐn)?shù)據(jù))
*/
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(@"接收到服務(wù)器的數(shù)據(jù)");
//拼接數(shù)據(jù)
[self.responseData appendData:data];
NSLog(@"%d---%@--",self.responseData.length,[NSThreadcurrentThread]);
}
/*
*當(dāng)服務(wù)器的數(shù)據(jù)加載完畢時(shí)就會(huì)調(diào)用
*/
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(@"服務(wù)器的數(shù)據(jù)加載完畢");
//隱藏HUD
[MBProgressHUDhideHUD];
//處理服務(wù)器返回的所有數(shù)據(jù)
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]);
}
/*
*請(qǐng)求錯(cuò)誤(失敗)的時(shí)候調(diào)用(請(qǐng)求超時(shí)\斷網(wǎng)\沒(méi)有網(wǎng)\返帕,一般指客戶(hù)端錯(cuò)誤)
*/
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
// ? ? NSLog(@"請(qǐng)求錯(cuò)誤");
//隱藏HUD
[MBProgressHUDhideHUD];
[MBProgressHUDshowError:@"網(wǎng)絡(luò)繁忙桐玻,請(qǐng)稍后重試!"];
}
另外荆萤,
NSMutableURLRequest是NSURLRequest的子類(lèi)镊靴,常用方法有
設(shè)置請(qǐng)求超時(shí)等待時(shí)間(超過(guò)這個(gè)時(shí)間就算超時(shí)铣卡,請(qǐng)求失敗)-(void)setTimeoutInterval:(NSTimeInterval)seconds;
設(shè)置請(qǐng)求方法(比如GET和POST)-(void)setHTTPMethod:(NSString*)method;
設(shè)置請(qǐng)求體-(void)setHTTPBody:(NSData*)data;
設(shè)置請(qǐng)求頭-(void)setValue:(NSString*)value forHTTPHeaderField:(NSString*)field;
使用NSURLConnection請(qǐng)求HTTPS(SSL)接口
//使用NSURLConnection連接HTTPS站點(diǎn)偏竟,需要處理SSL認(rèn)證煮落,NSURLConnectionDelegate中定義了一些方法來(lái)處理認(rèn)證
//–connection:canAuthenticateAgainstProtectionSpace:
//–connection:didReceiveAuthenticationChallenge:
//一.NSURLConnection中處理SSL
-(BOOL)connection:(NSURLConnection*)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace{
return[protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
//如果接受任何證書(shū)
-(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge{
[challenge.sender useCredential:[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust]forAuthenticationChallenge:challenge];
}
//如果使用證書(shū)驗(yàn)證
-(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類(lèi)的下面兩個(gè)方法,分別將上述代碼以block方式傳入即可踊谋。
–setAuthenticationAgainstProtectionSpaceBlock:
–setAuthenticationChallengeBlock: