NSURLConnection初步理解

        NSURLConnection網絡請求,是蘋果自帶的類。現在用的比較少了,一般都是用第三方框架,但是內部的實現還是通過NSURLConnection或者NSURLSession(是對前者的封裝)實現的;所以說還是需要了解;
        網絡請求現在基本分爲兩類:Get和Post,Get一般用來獲取數據,Post用上傳數據;NSURLConnection默認的是Get;
        Get的請求體都是和URL用'?'連接;而Post都是存在請求體中;並且請求體的大小沒有限制;

首先在創建網絡連接時;需要地址(URL),請求(NSURLRequest);最後纔是連接網絡請求;
//確定請求路徑
NSURL *url = [NSURL URLWithString:@"http://連接地址"];

//創建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];

/*
如果需要更改請求方法:
request.HTTPMethod = @"POST";

拼接請求體:
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@",self.userName.text,self.pwd.text];
設置請求體
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
*/

//3.發送請求
//請求分爲異步發送和同步發送;
/*同步請求,需要傳遞響應頭地址和錯誤信息儲存地址;而且有服務器返回的,需要接收;
NSURLResponse *response = nil; //這是創建的響應頭;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
*/

/*異步請求:參數1:請求;參數2:回調的隊列;參數3:請求完成後需要執行的操作;
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {

        }else {
                // NSHTTPURLResponse是響應頭實際的類型;statusCode是響應的狀態:200:成功,500:服務器故障,404:找不到資源,400:客戶端訪問錯誤;
                NSHTTPURLResponse *respon = (NSHTTPURLResponse *)response;
                NSLog(@"%zd--%@",respon.statusCode,respon.allHeaderFields);

                //4.解析響應體;
                NSString *res = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"%@---%@",res,[NSThread currentThread]);
        }
}];


//設置代理,發送異步請求,可以做一些監測,需要實現代理方法;
//第一種方法:
//[NSURLConnection connectionWithRequest:request delegate:self];

//第二種方法:
// NSURLConnection *connt = [[NSURLConnection alloc]initWithRequest:request delegate:self];

//第三種方法:和第二種唯一的區別是不會馬上提交連接;需要手動開啓;
NSURLConnection *connt = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
[connt start];
*/


代理方法使用,相信根據參數名字,很容易知道是什麼時候調用的:
//1.當接收到服務器響應的時候調用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
        NSLog(@"---didReceiveResponse-");
}

//2.當接收到服務器返回數據的時候調用,接收的數據不是一次性接收;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
        NSLog(@"---didReceiveData-%zd",data.length);
}
//3.當請求結束之後調用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
        NSLog(@"---connectionDidFinishLoading-");
}
//4.當請求失敗之後調用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
        NSLog(@"---didFailWithError-");
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章