你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> Iphone HTTP請求工具類詳解

Iphone HTTP請求工具類詳解

編輯:IOS開發綜合

在項目中我封裝了個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的專欄

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved