实现一个简单的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 ...
随机推荐
- python 缩进导致的问题
今天写Python 看着没有问题 运行就各种问题 object has no attribute 最后发现 Vim 设置里面有个 tabstop 我设置的是4 应该设置成8
- YII与Ace Admin 的集成
目录 一. 前言... 1 二.为什么要使用YII+ace. 1 三.新建YII模块... 1 四.如何修改模板... 3 五.注意的地方... 4 六.整合的不足之处... 4 一. 前言 yii- ...
- Java的跨平台原理
JAVA的跨平台原理 JAVA的跨平台原理 Java是一种简单易用.完全面向对象.有平台无关性.安全可靠的.主要面向Internet的开发工具.Java自从1995年正式面世以来,它的快速发展已经使整 ...
- DOCTYPE声明的几种类型
DOCTYPE声明的几种类型 DOCTYPE 声明决定着浏览器怎么去解析和渲染当前页面,所以对于页面来说是很重要的. HTML5时代,统一用 <!DOCTYPE html> 这样简单的方式 ...
- semver语义化版本号
semver语义化版本号 语义化版本号各位置的含义 版本号:X.Y.Z X: 代表发生了不兼容的API改变 Y: 代表向后兼容的功能性变化 Z: 代表向后兼容bug fixes 语义化版本号示例 1. ...
- 什么是LED锡膏?
LED锡膏熔点172℃,俗称中温锡膏,其合金为Sn64Bi35Ag1,此类产品是含Bi类的低熔点无铅锡膏,加入Ag改变了SnBi合金的焊点的机械强度.大幅度提高焊点可靠性,适用于高频调谐器系列产品的贴 ...
- css hr 设置
http://www.sovavsiti.cz/css/hr.html http://adamculpepper.net/blog/css/hr-tag-css-styling-cross-brows ...
- rsyslog 传输日志
nginx 服务器: front-end:/usr/local/nginx/logs# cat /etc/rsyslog.conf | grep -v "^$" | grep -v ...
- ollicle.com: Biggerlink – jQuery plugin
ollicle.com: Biggerlink – jQuery plugin Biggerlink – jQuery plugin Purpose Demo Updated for jQuery 1 ...
- php操作xml详解
XML是一种流行的半结构化文件格式,以一种类似数据库的格式存储数据.在实际应用中,一些简单的.安全性较低的数据往往使用 XML文件的格式进行存储.这样做的好处一方面可以通过减少与数据库的交互性操作提高 ...