STHTTPRequest
人类使用的NSURLSession包装器
简单...
- 1000行您能看懂的Objective-C代码
- 支持iOS 7+和Mac OS X 10.7+
- 只需将.h和.m文件拖放到您的项目中即可
- CocoaPods中使用pod 'STHTTPRequest'
- 新BSD许可
...但功能强大
- 同步和异步(基于块的)调用
- 轻松设置请求头、Cookie和POST数据
- 轻松获取响应状态、头和编码
- 带有进度块的文件上传
- 可以使用带有下载进度块的流式传输
- 快速简便的HTTP身份验证
- 以curl格式记录请求
典型用法
Objective-C
STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://google.com"];
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
// ...
};
r.errorBlock = ^(NSError *error) {
// ...
};
[r startAsynchronous];
Swift
let r = STHTTPRequest(URLString:"http://www.google.com")
r.completionBlock = { (headers, body) in
// ...
}
r.errorBlock = { (error) in
// ...
}
r.startAsynchronous()
备注
- STHTTPRequest 必须在主线程中使用
- 所有块都保证在主线程中调用
NSError *error = nil;
NSString *body = [r startSynchronousWithError:&error];
NSInteger status = r.responseStatus;
NSDictionary *headers = r.responseHeaders;
NSString *encoding = r.responseStringEncodingName;
NSData *data = r.responseData;
[r setHeaderWithName:@"test" value:@"1234"];
[r addCookieWithName:@"test" value:@"1234"];
[r setUsername:@"test" password:@"1234"];
r.GETDictionary = @{ @"paperid":@"6", @"q77":"1", @"q80":@"hello" };
r.POSTDictionary = @{ @"paperid":@"6", @"q77":"1", @"q80":@"hello" };
POST原始数据
request.rawPOSTData = myData;
上传文件
[r addFileToUpload:@"/tmp/photo.jpg" parameterName:@"photo"];
上传图片并设置参数
NSData *imageData = [NSData dataWithContentsOfFile:"image.jpg"];
[request addDataToUpload:imageData parameterName:@"param" mimeType:@"image/jpeg" fileName:@"file_name"];
上传多个图片
[request addDataToUpload:data1 parameterName:@"p1" mimeType:@"image/jpeg" fileName:@"name1"];
[request addDataToUpload:data2 parameterName:@"p2" mimeType:@"image/jpeg" fileName:@"name2"];
仅获取标题
r.HTTPMethod = @"HEAD";
设置下载进度的块
r.downloadProgressBlock = ^(NSData *dataJustReceived,
NSInteger totalBytesReceived,
NSInteger totalBytesExpectedToReceive) {
// notify user of download progress
// use the stream
}
在单元测试中可用
演示项目包含两个单元测试目标。
AsynchronousTests
展示了如何在单元测试中执行真正的网络请求。
STHTTPRequestTests
展示了如何通过使用伪响应填充队列来执行同步测试。只需将UnitTestAdditions 目录包含到您的项目中。
记录请求
要记录可读的调试描述,请添加启动参数 -STHTTPRequestShowDebugDescription 1
。
GET https://raw.github.com/github/media/master/octocats/octocat.png
HEADERS
Cookie = asd=sdf; xxx=yyy
COOKIES
asd = sdf
xxx = yyy
要记录curl描述,请添加启动参数 -STHTTPRequestShowCurlDescription 1
。
$ curl -i \
-b "asd=sdf;xxx=yyy" \
-H "Cookie: asd=sdf; xxx=yyy,asd=sdf; xxx=yyy" \
"https://raw.github.com/github/media/master/octocats/octocat.png"
(Curl 是随 OS X 一起提供的一款命令行工具,可以构建 HTTP 请求。)
支持
如果您有任何疑问,请在 GitHub 上创建一个问题或使用 StackOverflow 上的 STHTTPRequest 标签。
BSD 3-Clause 许可证
参见 LICENCE.txt。