1.NSURLConnection
2.AFNetworking
3.CFNetwork
//NSURLConnection
//發(fā)送同步請求代碼
// ? ?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.創(chuàng)建請求對象
NSURLRequest*request=[NSURLRequestrequestWithURL:url];
// ? ?3.發(fā)送請求
//發(fā)送同步請求,在主線程執(zhí)行
NSData*data=[NSURLConnectionsendSynchronousRequest:request returningResponse:nil error:nil];
//(一直在等待服務器返回數(shù)據(jù),這行代碼會卡住,如果服務器沒有返回數(shù)據(jù),那么在主線程UI會卡住不能繼續(xù)執(zhí)行操作)
NSLog(@"--%d--",data.length);
//發(fā)送異步請求代碼
// ? ?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.創(chuàng)建請求對象
NSURLRequest*request=[NSURLRequestrequestWithURL:url];
// ? ?3.發(fā)送請求
//3.1發(fā)送同步請求,在主線程執(zhí)行
// ? ?NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//(一直在等待服務器返回數(shù)據(jù),這行代碼會卡住,如果服務器沒有返回數(shù)據(jù),那么在主線程UI會卡住不能繼續(xù)執(zhí)行操作)
//3.1發(fā)送異步請求
//創(chuàng)建一個隊列(默認添加到該隊列中的任務異步執(zhí)行)
// ? ?NSOperationQueue *queue=[[NSOperationQueue alloc]init];
//獲取一個主隊列
NSOperationQueue*queue=[NSOperationQueuemainQueue];
[NSURLConnectionsendAsynchronousRequest:requestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError){
NSLog(@"--block回調數(shù)據(jù)--%@---%d",[NSThreadcurrentThread],data.length);
//隱藏HUD,刷新UI的操作一定要放在主線程執(zhí)行
[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(@"請求發(fā)送完畢");
//使用異步方法發(fā)送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創(chuàng)建請求對象
// ? ?NSURLRequest *request=[NSURLRequest requestWithURL:url];//默認就是GET請求
//設置請求超時
NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:url];
request.timeoutInterval=5.0;
// ? 2.3.發(fā)送請求
//使用代理發(fā)送異步請求(通常應用于文件下載)
NSURLConnection*conn=[NSURLConnectionconnectionWithRequest:requestdelegate:self];
[conn start];
NSLog(@"已經發(fā)出請求---");
}
#pragmamark-NSURLConnectionDataDelegate代理方法
/*
*當接收到服務器的響應(連通了服務器)時會調用
*/
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
NSLog(@"接收到服務器的響應");
//初始化數(shù)據(jù)
self.responseData=[NSMutableDatadata];
}
/*
*當接收到服務器的數(shù)據(jù)時會調用(可能會被調用多次,每次只傳遞部分數(shù)據(jù))
*/
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(@"接收到服務器的數(shù)據(jù)");
//拼接數(shù)據(jù)
[self.responseData appendData:data];
NSLog(@"%d---%@--",self.responseData.length,[NSThreadcurrentThread]);
}
/*
*當服務器的數(shù)據(jù)加載完畢時就會調用
*/
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(@"服務器的數(shù)據(jù)加載完畢");
//隱藏HUD
[MBProgressHUDhideHUD];
//處理服務器返回的所有數(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]);
}
/*
*請求錯誤(失敗)的時候調用(請求超時\斷網(wǎng)\沒有網(wǎng)\,一般指客戶端錯誤)
*/
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
// ? ? NSLog(@"請求錯誤");
//隱藏HUD
[MBProgressHUDhideHUD];
[MBProgressHUDshowError:@"網(wǎng)絡繁忙,請稍后重試!"];
}
另外,
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: