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];

实现一个简单的http请求工具类的更多相关文章

  1. 一个简单IP防刷工具类, x秒内最多允许y次单ip操作

    IP防刷,也就是在短时间内有大量相同ip的请求,可能是恶意的,也可能是超出业务范围的.总之,我们需要杜绝短时间内大量请求的问题,怎么处理? 其实这个问题,真的是太常见和太简单了,但是真正来做的时候,可 ...

  2. 一个简单的Java文件工具类

    package com.xyworkroom.ntko.util; import java.io.File; import java.io.FileInputStream; import java.i ...

  3. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  4. java模板模式项目中使用--封装一个http请求工具类

    需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...

  5. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  6. 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil

    基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...

  7. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  8. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  9. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

随机推荐

  1. BZOJ 4199: [Noi2015]品酒大会( 后缀数组 + 并查集 )

    求出后缀数组后, 对height排序, 从大到小来处理(r相似必定是0~r-1相似), 并查集维护. 复杂度O(NlogN + Nalpha(N)) ------------------------- ...

  2. [C#参考]主线程和子线程之间的参数传递

    几个进程在大多数情况下要包含很多的子线程,那么他们之间免不了的要互相传递很多的参数,那么参数怎么传递的呢? 主线程向子线程传递参数的方法 第一种方法:Thraed类有一个带参数的委托类型的重载形式,这 ...

  3. POJ1323-Game Prediction

    描述: Suppose there are M people, including you, playing a special card game. At the beginning, each p ...

  4. Android 内部存储安装apk文件实现

    目前国内市场的山寨机横行,安卓手机升级也是一天一个样,对于原来老手机可能没有SDCARD,导致我们的APP不能下载资源,无法更新APP,针对这种情况有以下解决方案.通过以下函数判断是否有SD卡再判断下 ...

  5. spoj 1557 GSS3 - Can you answer these queries III 线段树

    题目链接 给出n个数, 2种操作, 一种是将第x个数改为y, 第二种是询问区间[x,y]内的最大连续子区间. 开4个数组, 一个是区间和, 一个是区间最大值, 一个是后缀的最大值, 一个是前缀的最大值 ...

  6. (Problem 19)Counting Sundays

    You are given the following information, but you may prefer to do some research for yourself. 1 Jan ...

  7. VC++或QT下 高精度 多媒体定时器

    在VC编程中,用SetTimer可以定义一个定时器,到时间了,就响应OnTimer消息,但这种定时器精度太低了.如果需要精度更高一些的定时器(精 确到1ms),可以使用下面的高精度多媒体定时器进行代码 ...

  8. Android Studio 中快速提取方法

    在开发过程中,有时在一个方法内部写了过多的代码,然后想要把一些代码提取出来封装下,分离开放在一个单独的方法里,可能你的做法是直接选中后Ctrl + 叉,或者 Ctrl + C,但在Android St ...

  9. cocos2dx 在mac下开发ios和android游戏

    这里主要说android,因为ios开发在文章 http://blog.csdn.net/itcastcpp/article/details/24792323 中已经说过. 1)打开工程 打开ecli ...

  10. Yii2简单纪要

    网上经常拿Yii来类比ROR,从MVC角度,使用体验及代码风格上确实有很多相似的地方.不过看配置文件发现Yii2不止是受rails的影响,同样有不少spring的影子,最明显的就是配置文件中很多IOC ...