实现一个简单的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 ...
随机推荐
- Csharp多态的实现(接口)
1.什么是接口 接口可以看做是一个标准, 所有继承的子类需要按照接口中声明的方法来 接口用关键字 interface 修饰,接口的名字一般是I.........able ,表示我有什么能力 接口一般是 ...
- Problem F: Exponentiation大数求幂
DescriptionProblems involving the computation of exact values of very large magnitude and precision ...
- ThinkPHP中的CURD操作
<?php //查询多条记录,返回二维数组 $result = M("admin")->select(); $result = M("admin") ...
- hdu 2471 简单DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2571 简单dp, dp[n][m] +=( dp[n-1][m],dp[n][m-1],d[i][k ...
- Junk-Mail Filter(并差集删点)
Junk-Mail Filter Time Limit: 15000/8000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...
- 百度 LBS 开放平台,开发人员众測计划正式启动
Hi各位亲爱滴开发人员: 你是否以前-- 期望第一时间率先接触到百度LBS开放平台的最新功能? 期望被邀请作为最最尊贵的首批试用志愿者感受志愿者的特权? 期望自己的意见被产品经理採纳.优化功能.从 ...
- 一步一步学c#(五):泛型
泛型 性能 泛型的一个重要的优点是性能.system.collections和system.collections.generic名称空间的泛型和非泛型集和类.对值类型使用非泛型集合类,在把值类型转换 ...
- Microsoft SQL Server 数据库 错误号大全
panchzh :Microsoft SQL Server 数据库 错误号大全0 操作成功完成. 1 功能错误. 2 系统找不到指定的文件. 3 系统找不到指定的路径. 4 系统无法打开文件. 5 拒 ...
- spring jar包冲突
在用Spring+Hibernate做项目时候遇到java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit 网上查得答案 环境 ...
- margin 属性的相关问题
1.margin 的IE6 双边距问题 问题描述:浮动的块挨边框的时候会产生双倍的边距 解决方案: 1.增加display:inline; 2.去除float属性 2.margin 的重叠问题 CSS ...