OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类
四个文件源码大致如下,还有优化空间
MYHttpRequest.h(类定义,类目定义)
#import <Foundation/Foundation.h> @class MYHttpResponse; @interface MYHttpRequest : NSObject
{
@private
NSString *url;
NSString *method; NSMutableDictionary *reqHeaders;
NSMutableDictionary *postForms;
NSMutableDictionary *postFiles;
} -(MYHttpResponse *)get:(NSString *)url;
-(MYHttpResponse *)post:(NSString *)url; @end @interface MYHttpRequest (Create) -(id)init;
-(void)dealloc; @end @interface MYHttpRequest (Config) -(void)setUrl:(NSString *)_url;
-(void)setMethod:(NSString *)_method;
-(void)setReqHeaders:(NSDictionary *)_rheaders;
-(void)setPostForms:(NSDictionary *)_pforms;
-(void)setPostFiles:(NSDictionary *)_pfiles; -(void)addHeaderName:(NSString *)headerName Value:(NSString *)headerValue;
-(void)addFormName:(NSString *)formName Value:(NSString *)formValue;
-(void)addFileFieldName:(NSString *)fieldName Data:(NSString *)filePath; @end
MYHttpRequest.m(类实现,类目实现,延展实现私有方法)
#import "MYHttpRequest.h"
#import "MYHttpResponse.h" @interface MYHttpRequest () -(NSURLRequest *)buildRequest;
-(MYHttpResponse *)sendRequest:(NSURLRequest *)req; @end @implementation MYHttpRequest -(MYHttpResponse *)get:(NSString *)_url
{
[self setUrl:_url];
[self setMethod:@"GET"]; NSURLRequest *req = [self buildRequest];
return [self sendRequest:req];
}
-(MYHttpResponse *)post:(NSString *)_url
{
[self setUrl:_url];
[self setMethod:@"POST"]; NSURLRequest *req = [self buildRequest];
return [self sendRequest:req];
} -(NSURLRequest *)buildRequest
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]]; if([[method uppercaseString] isEqualToString:@"GET"]){
[request setHTTPMethod:@"GET"];
return request;
} [request setHTTPMethod:@"POST"]; NSArray *keys; NSString *boundary = [NSString stringWithFormat:@"---------------------------%f",[[NSDate date] timeIntervalSince1970]];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *postData = [NSMutableData data]; //Append Header
keys = [reqHeaders allKeys];
for (NSString *_key in keys)
{
[request addValue:[reqHeaders objectForKey:_key] forHTTPHeaderField: _key];
} //Append Post Forms
keys = [postForms allKeys];
for (NSString *_key in keys)
{
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", _key] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: text/plain\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"%@", [postForms objectForKey:_key]] dataUsingEncoding:NSUTF8StringEncoding]];
} // Append the Files
keys = [postFiles allKeys];
for (NSString *_key in keys)
{
NSString *filePath = [postFiles objectForKey:_key]; [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", filePath]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; NSData *photo = [[NSFileManager defaultManager] contentsAtPath:filePath];
[postData appendData:[NSData dataWithData:photo]];
} // Close
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // Append
[request setHTTPBody:postData]; return request;
} -(MYHttpResponse *)sendRequest:(NSURLRequest *)req
{
MYHttpResponse *myresponse = nil; NSURLResponse *response;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error) {
NSLog(@"Something wrong: %@",[error description]);
}else {
NSString *responseString = nil;
if (responseData) {
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = [httpResponse statusCode];
NSDictionary *responseHeaders = [httpResponse allHeaderFields]; myresponse = [[MYHttpResponse alloc] initWithCode:statusCode Headers:responseHeaders Body:responseString]; [responseString release];
}
[myresponse autorelease]; return myresponse;
} @end @implementation MYHttpRequest (Create) -(id)init
{
if (self=[super init]) {
url = [[NSString alloc] init];
method = [[NSString alloc] init]; reqHeaders = [[NSMutableDictionary alloc] init];
postForms = [[NSMutableDictionary alloc] init];
postFiles = [[NSMutableDictionary alloc] init];
}
return self;
} -(void)dealloc
{
[url release];
[method release]; [reqHeaders release];
[postForms release];
[postFiles release]; [super dealloc];
} @end @implementation MYHttpRequest (Config) -(void)setUrl:(NSString *)_url
{
if(url != _url)
{
[url release];
url = [_url retain];
}
}
-(void)setMethod:(NSString *)_method
{
if(method != _method)
{
[method release];
method = [_method retain];
}
}
-(void)setReqHeaders:(NSMutableDictionary *)_rheaders
{
if(reqHeaders != _rheaders)
{
[reqHeaders release];
reqHeaders = [_rheaders retain];
}
}
-(void)setPostForms:(NSMutableDictionary *)_pforms
{
if(postForms != _pforms)
{
[postForms release];
postForms = [_pforms retain];
}
}
-(void)setPostFiles:(NSMutableDictionary *)_pfiles
{
if(postFiles != _pfiles)
{
[postFiles release];
postFiles = [_pfiles retain];
}
} -(void)addHeaderName:(NSString *)headerName Value:(NSString *)headerValue
{
[reqHeaders setValue:headerValue forKey:headerName];
}
-(void)addFormName:(NSString *)formName Value:(NSString *)formValue
{
[postForms setValue:formValue forKey:formName];
}
-(void)addFileFieldName:(NSString *)fieldName Data:(NSString *)filePath
{
[postFiles setValue:filePath forKey:fieldName];
} @end
MYHttpResponse.h
#import <Foundation/Foundation.h> @interface MYHttpResponse : NSObject
{
} @property(nonatomic) NSInteger statusCode;
@property(nonatomic, retain) NSDictionary *responseHeaders;
@property(nonatomic, copy) NSString *responseBody; @end @interface MYHttpResponse (Create) -(id)init; -(id)initWithCode:(NSInteger)sCode
Headers:(NSDictionary *)rHeaders
Body:(NSString *)rBody; -(id)initWithCode:(NSInteger)sCode
Body:(NSString *)rBody; -(id)initWithBody:(NSString *)rBody; @end
MYHttpResponse.m
#import "MYHttpResponse.h" @implementation MYHttpResponse @synthesize statusCode;
@synthesize responseHeaders, responseBody; @end @implementation MYHttpResponse (Create) -(id)init
{
if (self=[super init]) {
}
return self;
} -(id)initWithCode:(NSInteger)sCode
Headers:(NSDictionary *)rHeaders
Body:(NSString *)rBody
{
if (self=[super init]) {
statusCode = sCode; self.responseHeaders = rHeaders;
self.responseBody = rBody;
}
return self;
} -(id)initWithCode:(NSInteger)sCode
Body:(NSString *)rBody
{
return [self initWithCode:sCode Headers:nil Body:rBody];
} -(id)initWithBody:(NSString *)rBody
{
return [self initWithCode: Headers:nil Body:rBody];
} @end
使用方法如下:
,引用头文件
#import "MYHttpRequest.h"
#import "MYHttpResponse.h" ,发起get请求
MYHttpRequest *request = [[MYHttpRequest alloc] init];
MYHttpResponse *response = [request get:@"http://localhost/get"]; NSLog(@"statuscode:%d",response.statusCode);
NSLog(@"headers:%@",response.responseHeaders);
NSLog(@"body:%@",response.responseBody); [request release]; ,发起post请求(multipart)
MYHttpRequest *request = [[MYHttpRequest alloc] init];
[request addHeaderName:@"Agent" Value:@"xiaomi"];
[request addFormName:@"uid" Value:@""];
MYHttpResponse *response = [request post:@"http://localhost/post"]; NSLog(@"statuscode:%d",response.statusCode);
NSLog(@"headers:%@",response.responseHeaders);
NSLog(@"body:%@",response.responseBody); [request release]; ,通过post请求上传文件
MYHttpRequest *request = [[MYHttpRequest alloc] init];
[request addFileFieldName:@"fileupload1" Data:@"/Users/penjin/Pictures/a.png"];
[request addFileFieldName:@"fileupload2" Data:@"/Users/penjin/Pictures/b.png"];
MYHttpResponse *response = [request post:@"http://localhost/postfile"]; NSLog(@"statuscode:%d",response.statusCode);
NSLog(@"headers:%@",response.responseHeaders);
NSLog(@"body:%@",response.responseBody); [request release];