Iphone HTTP請求工具類詳解

來源:互聯網
上載者:User

在項目中我封裝了個http請求的工具類,因為項目中只用到post請求,所以get請求的方法只是剛開始試了下,行得通,不知到有沒有錯誤,代碼如下:
h檔案:
[cpp]
#import <Foundation/Foundation.h> 
 
/*
 *自訂http代理
 */ 
@protocol MyhttpUitlDelegate <NSObject> 
-(void) setServicereturnData:(NSString*)servicedata; 
@end 
 
@interface MyHTTPUtil : NSObject<NSXMLParserDelegate> { 
    NSMutableData *webData;//非同步請求返回回來的資料 
     
    id<MyhttpUitlDelegate> myhttputildelegate; 
    NSString *dialogcanshow;//防止快速兩次請求以上彈出多個等待對話筐 
     
    //等待對話筐 
    UIAlertView *mt; 

 
@property(nonatomic,retain)id<MyhttpUitlDelegate> myhttputildelegate; 
@property(nonatomic,retain)UIAlertView *mt; 
@property(nonatomic,retain) NSString *dialogcanshow;//防止快速兩次請求以上彈出多個等待對話筐 
 
+(NSString *)httpForTongbuGET:(NSString *)urlstring; 
+(NSString *)httpForTongbuPOST:(NSString *)urlstring addParms:(NSData *)urlparms; 
//-(void)httpForYibuPOST:(NSString *)urlstring addParms:(NSString *)urlparms; 
-(void)httpForYibuPOSTForData:(NSString *)urlstring addParms:(NSData *)urlparms; 
-(void)httpForYibuGET:(NSString *)urlstring addParms:(NSString *)urlparms; 
-(void)httpForYibuPOSTPageparms:(NSString *)urlstring addParms:(NSData *)pageparms; 
-(void)showwaitalertview; 
 
@end 

m檔案
[cpp]
#import "MyHTTPUtil.h" 
#import "FileUtils.h" 
 
@implementation MyHTTPUtil 
//url公用部分 
//NSString *baseurl = @"http://192.168.0.63:8080/mbtravel/"; 
//NSString *baseurl = @"http://192.168.0.63:8081/mbtr/"; 
NSString *baseurl = @"http://192.168.128.1:8080/mbtravel/"; 
NSInteger PagingRows = 5;//每頁的行數 
@synthesize myhttputildelegate; 
@synthesize dialogcanshow; 
@synthesize mt; 
 
-(void)dealloc{ 
    [myhttputildelegate release]; 
    [dialogcanshow release]; 
    [mt release]; 
    [super dealloc]; 

 
-(id)init{ 
    self.dialogcanshow = @"false"; 
   return  [super init]; 

 
//http的同步get請求,返回伺服器返回的資料 
+(NSString *)httpForTongbuGET:(NSString *)urlstring{ 
    NSString *allurl = [NSString stringWithFormat:@"%@%@",baseurl,urlstring]; 
    NSURL* url = [NSURL URLWithString:allurl];   
     
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc]init]autorelease];  
    [request setURL:url];   
    [request setHTTPMethod:@"GET"];  
    NSString *contentType = [NSString stringWithFormat:@"text/xml"];//@"application/json"  
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; 
    NSHTTPURLResponse *urlResponese = nil; 
    NSError *error = [[NSError alloc]init]; 
    NSData* data = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];  
    NSString* result= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){ 
         
        return result; 
    } 
    return nil; 
    [error release]; 
    [result release]; 

 
 
//非同步get請求 
-(void)httpForYibuGET:(NSString *)urlstring addParms:(NSString *)urlparms{ 
    //    if ([ValueUtils caseEquals:self.dialogcanshow to:@"true"]){ 
    //        [self showwaitalertview];//彈出等待對話筐 
    //    } 
    //     
    NSString *allurl = [NSString stringWithFormat:@"%@%@%@",baseurl,urlstring,urlparms]; 
    NSLog(@"%@",allurl); 
    NSURL *url = [NSURL URLWithString:allurl];                            
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];   
     
    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    //[theRequest setTimeoutInterval:15];//設定了也是無效 
    [theRequest setHTTPMethod:@"GET"];  
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
     
    if(theConnection) { 
        webData = [[NSMutableData data] retain]; 
         
    } 

// 
////非同步post請求,帶參數 
// 
//-(void)httpForYibuPOST:(NSString *)urlstring addParms:(NSString *)urlparms{ 
////    if ([ValueUtils caseEquals:self.dialogcanshow to:@"true"]) { 
////        [self showwaitalertview];//彈出等待對話筐 
////    } 
//     
//    NSString *allurl = [NSString stringWithFormat:@"%@%@%@",baseurl,urlstring,urlparms]; 
//          //NSStringEncoding  enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);   //轉換編碼,包括中文 
//   // NSString *allurl2=[allurl stringByAddingPercentEscapesUsingEncoding:enc]; 
//   NSString *allurl2= [allurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
//    NSLog(@"url===%@",allurl2); 
//    NSURL *url = [NSURL URLWithString:allurl2];    
//    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];   
//    [theRequest  setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"]; 
//      [theRequest  setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"]; 
//    [theRequest addValue: @"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
//    //[theRequest setTimeoutInterval:15];//設定了也是無效 
//    [theRequest setHTTPMethod:@"POST"];  
//    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
//     
//     
//    if(theConnection) { 
//        webData = [[NSMutableData data] retain]; 
//         
//    } 
//} 
 
 
 
//基本上只用下面這三個方法 
 
 
//http的同步post請求,返回伺服器返回的資料 
+(NSString *)httpForTongbuPOST:(NSString *)urlstring addParms:(NSData *)urlparms{ 
    NSString *allurl = [NSString stringWithFormat:@"%@%@",baseurl,urlstring]; 
    NSURL* url = [NSURL URLWithString:allurl];   
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc]init]autorelease];  
    [request setURL:url];   
    [request setHTTPMethod:@"POST"];  
    [request  setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"]; 
    [request  setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"]; 
    [request addValue: @"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
   // [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];//寫這句而不是上面那句,就會出錯 
     [request setHTTPBody:urlparms];   
    NSHTTPURLResponse *urlResponese = nil; 
    NSError *error = [[NSError alloc]init]; 
    NSData* data = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];  
    NSString* result= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){ 
         
        return result; 
    } 
    return nil; 
    [error release]; 
    [result release]; 

 
 
//非同步post請求,後面參數是nsdata類型,主要針對參數提交 
-(void)httpForYibuPOSTForData:(NSString *)urlstring addParms:(NSData *)urlparms{ 
    NSString *allurl = [NSString stringWithFormat:@"%@%@",baseurl,urlstring]; 
    NSString *allurl2= [allurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSURL *url = [NSURL URLWithString:allurl2];    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];   
    [theRequest  setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"]; 
    [theRequest  setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"]; 
    [theRequest addValue: @"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
    [theRequest setHTTPMethod:@"POST"];  
    [theRequest  setValue:[NSString stringWithFormat:@"%d",PagingRows] forHTTPHeaderField:@"PagingRows"]; 
    [theRequest setHTTPBody:urlparms]; 
     
    if ([ValueUtils caseEquals:self.dialogcanshow to:@"true"]){ 
        [self showwaitalertview];//彈出等待對話筐 
    } 
     
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
     
    if(theConnection) { 
        webData = [[NSMutableData data] retain]; 
         
    } 
 

 
//非同步post請求,主要針對分頁查詢 
-(void)httpForYibuPOSTPageparms:(NSString *)urlstring addParms:(NSData *)pageparms{ 
    //    if ([ValueUtils caseEquals:self.dialogcanshow to:@"true"]) { 
    //        [self showwaitalertview];//彈出等待對話筐 
    //    } 
     
    NSString *allurl = [NSString stringWithFormat:@"%@%@",baseurl,urlstring]; 
    NSString *allurl2= [allurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSURL *url = [NSURL URLWithString:allurl2];    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];   
    [theRequest  setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"]; 
    [theRequest  setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"]; 
    [theRequest addValue: @"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
    [theRequest setHTTPMethod:@"POST"];  
    [theRequest  setValue:[NSString stringWithFormat:@"%d",PagingRows] forHTTPHeaderField:@"PagingRows"]; 
    [theRequest setHTTPBody:pageparms]; 
     
    if ([ValueUtils caseEquals:self.dialogcanshow to:@"true"]){ 
        [self showwaitalertview];//彈出等待對話筐 
    } 
     
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
     
     
    if(theConnection) { 
        webData = [[NSMutableData data] retain]; 
         
    } 

 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    [webData setLength:0]; 
//    if ([ValueUtils caseEquals:self.dialogcanshow to:@"true"]){ 
//        [self showwaitalertview];//彈出等待對話筐 
//    } 
     

 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [webData appendData:data]; 

 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    if (mt!=nil) { 
      [mt dismissWithClickedButtonIndex:1 animated:YES]; 
    } 
    [self performSelectorInBackground:@selector(showerroralertview) withObject:nil];  
    //[mt dismissWithClickedButtonIndex:1 animated:YES]; 

 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    if (mt!=nil) { 
        [mt dismissWithClickedButtonIndex:1 animated:YES]; 
    } 
    [connection release]; 
     
    NSString* result= [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding]; 
    [self.myhttputildelegate setServicereturnData:result];//為頁面設值 
    [webData release]; 
    [result release]; 

//彈出error對話筐 
-(void)showerroralertview{ 
    UIAlertView *erroralert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"請求資料失敗" delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定", nil]; 
    [erroralert show]; 
    [erroralert release]; 
     

 
//彈出等待對話筐 
-(void)showwaitalertview{ 
    mt = [[UIAlertView alloc]initWithTitle:nil message:@"正在載入......" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil]; 
    [mt show]; 
    
 

 
 
 
@end 



摘自 RiverAM的專欄

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.