自己写的网络数据请求没有第三方框架 支持字节流数据
最近项目中上传地图围栏总是使用字节流上传加上其他数据请求 所以整合在一起了,直接上代码
#import <Foundation/Foundation.h>
@interface HTTPRequest : NSObject
+ (HTTPRequest *)shared;
- (void)testPost;
#pragma mark - 网络请求方法
/**
网络数据请求
@param rootUrl 网络请求根地址,例:http://locatore.net/q3/v2/
@param portStr 接口名称,例:follow
@param params 网络请求参数,NSDictionry格式
@param completeHandler 回调
*/
- (void)startNetRequestWithRootUrl:(NSString *)rootUrl portStr:(NSString *)portStr params:(NSDictionary *)params completeHandler:(HTTPRequestCompletedHandler)completeHandler;
- (void)testHttps;
#import "HTTPRequest.h"
@interface HTTPRequest () <NSURLSessionDelegate>
@end
@implementation HTTPRequest
+ (HTTPRequest *)shared
{
static HTTPRequest *obj = nil;
if (obj == nil) {
obj = [[self alloc] init];
}
return obj;
}
#pragma mark - 网络请求
- (void)startNetRequestWithRootUrl:(NSString *)rootUrl portStr:(NSString *)portStr params:(NSDictionary *)params completeHandler:(HTTPRequestCompletedHandler)completeHandler
{
if (portStr == nil) portStr = @"";
NSString *originUrl = [NSString stringWithFormat:@"%@%@", rootUrl, portStr];
NSString *method = @"POST";
BOOL isV3 = [V3ROOTURL isEqualToString:rootUrl];
CGFloat multi = (isV3) ? 1.0 : 1000.0;
NSDictionary *paramsDict = [MYGLOBAL getSignedParamsDictWithUrl:originUrl params:params method:method multi:multi];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:originUrl]];
[request setHTTPMethod:@"POST"];
[self bulildBodyForRequest:request withParams:paramsDict isV3:isV3];
//请求历史轨迹的坐标点,服务器返回的数据为字节流,用AFNetworking请求会报错,所以改用NSURLSession
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *resultDict = nil;
NSString *errorMsg = nil;
if (error) {
//NSLog(@"Error: %@", error);
errorMsg = error.localizedDescription;
} else {
resultDict = [MYGLOBAL readStreamByteDataWithData:data];
if ([V3ROOTURL isEqualToString:rootUrl]) {
//新接口的错误返回用status标识,OK为正确,KO为错误
if (resultDict && (![@"OK" isEqualToString:resultDict[@"status"]] || resultDict[@"errmsg"])) {
errorMsg = resultDict[@"errmsg"];
}
}else{
//旧接口如果返回errcode不为0,说明有错误返回
if (resultDict && ([resultDict[@"errcode"] intValue] != 0 || resultDict[@"errmsg"])) {
errorMsg = resultDict[@"errmsg"];
}
}
if (resultDict == nil) {
NSLog(@"responsStr:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}
dispatch_async(dispatch_get_main_queue(), ^{
if (completeHandler) completeHandler(resultDict, errorMsg);
});
}];
[dataTask resume];
}
- (void)testPost
{
// NSString *urlStr = @"http://localhost/test/testPost.php";
// NSURL *url = [NSURL URLWithString:urlStr];
//
// NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Contact_name_textfield.png" ofType:nil];
// NSData *fileData = [NSData dataWithContentsOfFile:filePath];
//
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// [request setHTTPMethod:@"POST"];
// NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// dict[@"imei"] = @"2103010151";
// dict[@"name"] = @"吴飞";
// dict[@"avatar"] = fileData;
//
// [self bulildBodyForRequest:request withParams:dict];
//
// [NSURLConnection sendAsynchronousRequest:request
// queue:[NSOperationQueue mainQueue]
// completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%@", responseStr);
// }];
}
- (void)testHttps
{
// NSString *urlStr = @"https://192.168.16.71/v3/app/list_acc_sub";
// NSDictionary *params = @{@"imei":@"好&=?/"};
// NSString *urlStr = @"http://115.29.249.239:8081/locator/q3/v2/login";
// NSDictionary *params = @{@"name":@"test234@qq.com",
// @"pwd":@"好"};
//
// NSDictionary *paramsDict = [MYGLOBAL getSignedParamsDictWithUrl:urlStr params:params method:@"POST" multi:1000.0];
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
// [request setHTTPMethod:@"POST"];
// [self bulildBodyForRequest:request withParams:paramsDict isV3:NO];
//
// NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//// NSURLSession *session = [NSURLSession sharedSession];
// NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// if (error) {
// NSLog(@"error:%@", error.localizedDescription);
// }else{
// NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"response:%@", responseStr);
// }
// }];
// [task resume];
NSDictionary *params = @{@"address" : @"Via Grazzini广东",
@"city" : @"Milano",
@"country" : @"Italy",
@"first_name" : @"Claudio",
@"fiscal_code" : @"pcccld74L31F205S",
@"last_name" : @"Picco",
@"uid" : @"ah8x0giu",
@"uname" : @"hu@163.com",
@"uphone" : @"+39141",
@"zipcode" : @"20158"};
[HTTPREQUEST startNetRequestWithRootUrl:V3ROOTURL
portStr:REQUEST_UpdateAccountInfo
params:params
completeHandler:^(NSDictionary *resultDict, NSString *errorMsg) {
if (errorMsg) {
NSLog(@"error:%@", errorMsg);
}else{
NSLog(@"%@", resultDict);
}
}];
}
#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
//AFNetworking中的处理方式
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
//判断服务器返回的证书是否是服务器信任的
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
/*disposition:如何处理证书
NSURLSessionAuthChallengePerformDefaultHandling:默认方式处理
NSURLSessionAuthChallengeUseCredential:使用指定的证书 NSURLSessionAuthChallengeCancelAuthenticationChallenge:取消请求
*/
if (credential) {
disposition = NSURLSessionAuthChallengeUseCredential;
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
//安装证书
if (completionHandler) {
completionHandler(disposition, credential);
}
}
- (void)bulildBodyForRequest:(NSMutableURLRequest *)request withParams:(NSDictionary *)dict isV3:(BOOL)isV3
{
BOOL isHaveFileData = NO;
NSArray *keysArr = [dict allKeys];
for (NSString *key in keysArr) {
id value = dict[key];
if ([value isKindOfClass:[NSData class]]) {
isHaveFileData = YES;
break;
}
}
NSMutableData *body = [NSMutableData data];
//如果有文件就用表单形式提交数据,没有就用URLEncode方式
if (isHaveFileData) {
CFUUIDRef uuid = CFUUIDCreate(nil);
NSString *uuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(nil, uuid));
CFRelease(uuid);
NSString *stringBoundary = [NSString stringWithFormat:@"0xKhTmLbOuNdArY-%@",uuidString];
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
[request addValue:[NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, stringBoundary] forHTTPHeaderField:@"Content-Type"];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableDictionary *strDict = [NSMutableDictionary dictionary];
NSMutableDictionary *fileDict = [NSMutableDictionary dictionary];
for (NSString *key in dict) {
id value = dict[key];
if ([value isKindOfClass:[NSData class]]) {
[fileDict setObject:value forKey:key];
}else{
[strDict setObject:value forKey:key];
}
}
// Adds post data
NSString *endItemBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary];
NSUInteger i=0;
for (NSString *key in strDict) {
NSString *value = strDict[key];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@", value] dataUsingEncoding:NSUTF8StringEncoding]];
i++;
if (i != [strDict count] || [fileDict count] > 0) { //Only add the boundary if this is not the last item in the post body
[body appendData:[endItemBoundary dataUsingEncoding:NSUTF8StringEncoding]];
}
}
// Adds files to upload
i=0;
for (NSString *key in fileDict) {
NSData *value = fileDict[key];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"filename\"\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: \r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:value];
i++;
// Only add the boundary if this is not the last item in the post body
if (i != [fileDict count]) {
[body appendData:[endItemBoundary dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request addValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setTimeoutInterval:OUTTIME * 2];
}else{
int i=0;
NSString *parmaStr = @"";
NSMutableCharacterSet *charset = [NSMutableCharacterSet letterCharacterSet];
[charset formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
for (NSString *key in keysArr) {
NSString *value = dict[key];
if ([value isKindOfClass:[NSString class]]) {
value = [value stringByAddingPercentEncodingWithAllowedCharacters:charset];
}
i++;
if (i != keysArr.count) {
parmaStr = [parmaStr stringByAppendingFormat:@"%@=%@&", key, value];
}else{
parmaStr = [parmaStr stringByAppendingFormat:@"%@=%@", key, value];
}
}
NSData *data = [parmaStr dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:data];
[request setTimeoutInterval:OUTTIME];
if (isV3) {
[request addValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request addValue:postLength forHTTPHeaderField:@"Content-Length"];
}
}
[request setHTTPBody:body];
}
@end
如果有需要代码的可以私信我.