iPHone 中用 NSURLRequest 模拟 POST 和GET 请求

来源:互联网 发布:php获取cookie 编辑:程序博客网 时间:2024/05/02 04:34

//

//  RESTHelper.h

//  Mainaer

//

//  Created by dhanzhang on 10-7-7.

//  Copyright 2010 http://hi.csdn.net/dhz123. All rights reserved.

//

 

#import <Foundation/Foundation.h>

 

/*

 

 用于发送 HTTP  请求的辅助类 

 封装  POST  请求

 

 */

 

@interface RESTHelper : NSObject  {

 

NSString  * requestUrlPath;

 

id  mdelegate;

SEL doneSelector;

    SEL errorSelector;

 

}

 

-(id)  initWithUrl:(NSString*) urlPath 

  postData:(NSDictionary*)  data

  delegate:(id)  aDelegate

onErrorCallback:(SEL) errorCallback

onCompletedCallback:(SEL) complectedCallback;

 

 

@end

-----------------------

//

//  RESTHelper.m

//  Mainaer

//

//  Created by dhanzhang on 10-7-7.

//  Copyright 2010 http://hi.csdn.net/dhz123. All rights reserved.

//

 

#import "RESTHelper.h"

 

 

#import "Log.h"

 

static NSString * const BOUNDRY        = @"--------------------------7d71a819230404";

 

 

@interface RESTHelper(Private) 

 

 

@end

 

 

@implementation  RESTHelper(Private) 

 

 

- (void)connection:(NSURLConnection *)connection   

  didFailWithError:(NSError *)error            {

    CMLog(@"NSURLCOnnection ERROR!");

 [mdelegate performSelector: errorSelector  withObject:error];

}

 

- (void)connection:(NSURLConnection *)connection     

didReceiveData:(NSData *)data              {

 CMLog(@"NSURLConnection ReceivedData!");

NSString *reply  =[ [NSString alloc] initWithData:data

encoding:NSUTF8StringEncoding] ;

 

    [mdelegate performSelectordoneSelector  withObject: reply];

[reply release];

}

 

 

@end

 

 

@implementation RESTHelper

 

 

-(id)  initWithUrl:(NSString*) urlPath 

  postData:(NSDictionary*)  data

  delegate:(id)  aDeletgate

onErrorCallback:(SEL) errorCallback

onCompletedCallback:(SEL) complectedCallback

{

if (self=[super init]) {

requestUrlPath =[[NSString stringWithString:  urlPath] lowercaseString] ;

mdelegate=[  aDeletgate retain];

errorSelector= errorCallback;

doneSelector = complectedCallback ;

NSURL  * url=[NSURL URLWithString:requestUrlPath] ;

NSMutableURLRequest  * req=[NSMutableURLRequest requestWithURL: url];

if (data != nil ) {

 

[req setHTTPMethod:@"POST"];

[reqsetValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDRY]

forHTTPHeaderField:@"Content-Type"];

 int len=512;

  NSMutableData  * postData =[NSMutableData dataWithCapacity:len];

 [postData  appendData: [[NSString  stringWithFormat:@"--%@/r/n",BOUNDRY

dataUsingEncoding:NSUTF8StringEncoding]];

 int  i=0;

int  cnt=data.count ;

 

for ( NSString * key in  [data allKeys]) 

{

[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=/"%@/"/r/n/r/n", key ] 

dataUsingEncoding:NSUTF8StringEncoding]];

[postData  appendData: [[NSString  stringWithFormat:@"%@",[data objectForKey:key ]] 

dataUsingEncoding:NSUTF8StringEncoding]];

if( i != cnt -1  ){

  [postData  appendData: [[NSString  stringWithFormat:@"/r/n--%@/r/n",BOUNDRY

dataUsingEncoding:NSUTF8StringEncoding]];

}

i++ ;

}

[postData  appendData:[[NSString stringWithFormat:@"/r/n--%@--/r/n",BOUNDRY]

  dataUsingEncoding:NSUTF8StringEncoding]];

[req  setHTTPBody:postData];

}

else {

[req  setHTTPMethod:@"GET"];

}

 

NSURLConnection * connection =[[[NSURLConnection alloc] initWithRequest:req delegate:self] autorelease];

if(!connection  ){ 

NSDictionary * errorInfo=[NSDictionary dictionaryWithObjectsAndKeys:@"发送请求失败" ,@"errorKey", nil];

NSError * error=[NSError  errorWithDomain:@"www.mainaer.com" code:100 userInfo:  errorInfo];

          [mdelegate performSelector:errorCallback withObject: error];

else {

CMLog(@"Send Data Request /n");

}

 

}

return self ;

}

 

 

- (void)dealloc

{

    [mdelegate release];

mdelegate = nil;

 

    doneSelector = NULL;

    errorSelector = NULL;

    [super dealloc];

}

 

 

@end

 ======================

调用方法:

 

NSDictionary  * loginData=[NSDictionary  dictionaryWithObjectsAndKeys

  txtUserName.text,@"UserName",

  txtPassword1.text,@"Password",

 txtPassword2.text,@"Password2",

  txtEmail.text,@"EMail",

  nil];

 

 

RESTHelper  * hlp =[[ RESTHelper  allocinitWithUrl:@"http://www.daihanzhang.com/Reg.ashx"

postData: loginData

delegateself

onErrorCallback:@selector(errorCallback:)

onCompletedCallback:@selector(completedCallback:)];

[hlp release]; 

 

------

 

-(void)  errorCallback:(NSError*) error;

 

/*数据下载完毕 */

-(void)  completedCallback:(NSString*) data;