实现一个简单的http请求工具类
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请求工具类的更多相关文章
- 一个简单IP防刷工具类, x秒内最多允许y次单ip操作
IP防刷,也就是在短时间内有大量相同ip的请求,可能是恶意的,也可能是超出业务范围的.总之,我们需要杜绝短时间内大量请求的问题,怎么处理? 其实这个问题,真的是太常见和太简单了,但是真正来做的时候,可 ...
- 一个简单的Java文件工具类
package com.xyworkroom.ntko.util; import java.io.File; import java.io.FileInputStream; import java.i ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
- java模板模式项目中使用--封装一个http请求工具类
需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil
基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
随机推荐
- 锁·——lock关键字详解
作 者:刘铁猛 日 期:2005-12-25 关键字:lock 多线程 同步 小序 锁者,lock关键字也.市面上的书虽然多,但仔细介绍这个keyword的书太少了.MSDN里有,但所给的代码非常 ...
- Spring学习之优缺点
Spring 1.Spring工作机制及为什么要用? Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.Spring既是一个AOP框架,也是一IOC容器. SpringFrame ...
- apktool 反翻译错误
-出现 UndefinedResObject Exception : 这是因为被反编译的apk中有当前的framework不支持的属性:解决方式如下: 1.删除C:\Users\Administrat ...
- WCF 接收、发送数据的大小及时间的设置
<system.serviceModel> <bindings> <basicHttpBinding> <binding name="/> & ...
- ny 58 最少步数 (BFS)
题目:http://acm.nyist.net/JudgeOnline/problem.php?pid=58 就是一道简单的BFS 练习练习搜索,一次AC #include <iostream& ...
- ngCookies模块
Angular中ngCookies模块介绍 1.Cookie介绍 Cookie总是保存在客户端中,按在客户端中的存储位置,可分为内存Cookie和硬盘Cookie.内存Cookie由浏览器维护,保存在 ...
- 转: javascript模块加载框架seajs详解
javascript模块加载框架seajs详解 SeaJS是一个遵循commonJS规范的javascript模块加载框架,可以实现javascript的模块化开发和模块化加载(模块可按需加载或全部加 ...
- 看日记学git摘要~灰常用心的教程
看日记学git linux 命令行 cd ls / ls -a clear mkdir rmdir echo "hi, good day" > hi.txt touch he ...
- 关于 overridePendingTransition()使用
实现两个 Activity 切换时的动画.在Activity中使用有两个参数:进入动画和出去的动画. 注意1.必须在 StartActivity() 或 finish() 之后立即调用.2.而且在 ...
- 20个经典bootsrtap后台html网站模板推荐
今天为大家推荐20款不同风格的Bootstrap后台管理模板,每一款都经典可用,能预览和下载,保证让你挑得眼花缭乱. 1,Simpli flag蓝色 Simpli Flat蓝色管理模板是一款采用Fla ...