You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

704 lines
31 KiB

//
// myHttp.m
// tianyin
//
// Created by xTT on 15/6/6.
// Copyright (c) 2015年 xTT. All rights reserved.
//
#import "MyHttp.h"
#import "AppDelegate.h"
#import "User.h"
#import "Device.h"
#import "Circle.h"
#define goLoginTag 100
#define goHomeTag 200
#define reQuestTag 300
#define updataTag 400
@interface MyHttp (){
NSString *reURLString;
NSDictionary *reParameters;
void (^reSuccess)(NSURLSessionDataTask *, id);
void (^reFailure)(NSURLSessionDataTask *task, NSError *error);
}
@end
@implementation MyHttp
+ (instancetype)sharedClient
{
static MyHttp *client = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
client = [[MyHttp alloc] initWithBaseURL:[NSURL URLWithString:xBaseUrl]];
client.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"GET", @"HEAD"]];
client.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/json",
@"text/javascript",
@"text/html", nil];
[client.reachabilityManager startMonitoring];
NSString *basicAuthStr = [NSString stringWithFormat:@"%@:%@",URL_username,URL_password];
NSData *basicAuthData = [basicAuthStr dataUsingEncoding:NSASCIIStringEncoding];
// 通过 ID :密码 的格式,用Basic 的方式拼接成字符串
NSString *basicAuthValue = [NSString stringWithFormat:@"Basic %@",[basicAuthData base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength]];
// 设置Authorization的方法设置header
[client.requestSerializer setValue:basicAuthValue forHTTPHeaderField:@"Authorization"];
// [client.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// [client setSecurityPolicy:[client customSecurityPolicy]];
});
return client;
}
- (AFSecurityPolicy*)customSecurityPolicy
{
/**** SSL Pinning ****/
// NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"app2g.mobilebrother.net" ofType:@"cer"];
// NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
// AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate
// withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];
// [securityPolicy setAllowInvalidCertificates:YES];
// 是否在证书域字段中验证域名
// AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
// [securityPolicy setValidatesDomainName:NO];
// **** SSL Pinning ***
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[securityPolicy setAllowInvalidCertificates:YES];
return securityPolicy;
}
- (NSDictionary *)addIdentify:(id)parameters URL:(NSString *)URLString{
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parameters];
[dic setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"identify"];
// xLog(@"parameters = %@ = %@",dic,URLString);
return dic;
}
- (NSURLSessionDataTask *)URL:(NSString *)URLString
method:(NSString *)method
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
return [self URL:URLString method:method parameters:parameters constructingBodyWithBlock:nil
success:success failure:failure];
}
- (NSURLSessionDataTask *)URL:(NSString *)URLString
method:(NSString *)method
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
showHUD:(BOOL)showHUD{
return [self URL:URLString method:method parameters:parameters constructingBodyWithBlock:nil
success:success failure:failure showHUD:showHUD]; //本来是写死 NO
}
- (NSURLSessionDataTask *)URL:(NSString *)URLString
method:(NSString *)method
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask * task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask * task, NSError * error))failure{
return [self URL:URLString method:method parameters:parameters constructingBodyWithBlock:block
success:success failure:failure showHUD:YES];
}
- (NSURLSessionDataTask *)URL:(NSString *)URLString
method:(NSString *)method
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
showHUD:(BOOL)showHUD{
return [self URL:URLString method:method parameters:parameters constructingBodyWithBlock:block
success:success failure:failure showHUD:showHUD showError:YES]; //本来是写死 YES
}
//- (void)setFormData:(id<AFMultipartFormData>)formData
// parameters:(id)parameters
// obj:(id)obj
// img:(UIImage *)img {
// if (img) {
// [formData appendPartWithFileData:UIImageJPEGRepresentation(img, 0.1)
// name:@"image"
// fileName:@"image.jpg"
// mimeType:@"image/jpeg"];
// }else if (obj){
// if ([obj isKindOfClass:[UIImage class]]) {
// [formData appendPartWithFileData:UIImageJPEGRepresentation(obj, 0.1)
// name:@"content"
// fileName:@"image.jpg"
// mimeType:@"image/jpeg"];
// }else if ([parameters[@"content_type"] isEqualToNumber:@(3)] ||
// [parameters[@"type"] isEqualToNumber:@(3)]){
// [formData appendPartWithFileData:obj
// name:@"content"
// fileName:@"voice"
// mimeType:@"amr"];
// }
// }
//}
- (NSURLSessionDataTask *)URL:(NSString *)URLString
method:(NSString *)method
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
showHUD:(BOOL)showHUD
showError:(BOOL)showError{
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[app beingBackgroundUpdateTask];
if (!parameters || [parameters isKindOfClass:[NSDictionary class]]) {
parameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
}
if ([User currentUser]) {
[parameters setObject:[User currentUser].openid forKey:@"openid"];
[parameters setObject:[User currentUser].accesstoken forKey:@"accesstoken"];
}
//MARK: 添加app版本号,BundleID,时区,语言等到头部
[self.requestSerializer setValue:kTOKEN_APP_VERSION forHTTPHeaderField:@"Version"];
[self.requestSerializer setValue:kTOKEN_APP_BUNDLEID forHTTPHeaderField:@"BundleId"];
[self.requestSerializer setValue:kTOKEN_APP_LANGUAGE forHTTPHeaderField:@"Accept-Language"];
[self.requestSerializer setValue:kTOKEN_APP_TIMEZONE forHTTPHeaderField:@"Timezone"];
if (showError &&
self.reachabilityManager.networkReachabilityStatus != AFNetworkReachabilityStatusUnknown &&
!self.reachabilityManager.isReachable) {
//[UICommon MessageErrorText:NSLocalizedStringFromTable(@"请检查您的网络设置", @"Localization", @"")];
[UICommon MessageErrorText:NSLocalizedStringFromTable(@"请检查您的网络设置", @"Localization", @"")];
[UICommon HidenLoading];
failure(nil,nil);
return nil;
}
if (showHUD) {
//[UICommon MessageUpload:@"正在加载"];
}
xLog(@"请求 %@ = %@ = %@",parameters,URLString,method);
NSURLSessionDataTask *dataTask = nil;
WEAKSELF
if ([method isEqualToString:@"POST"]) {
if (block) {
dataTask = [super POST:URLString
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[UICommon HidenLoading];
if (block) {
block(formData);
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
// xLog(@"%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[UICommon HidenLoading];
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}else{
dataTask = [super POST:URLString parameters:parameters
progress:^(NSProgress * _Nonnull uploadProgress) {
// xLog(@"%@",uploadProgress);
}success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}
}else if([method isEqualToString:@"GET"]){
dataTask = [super GET:URLString parameters:parameters
progress:^(NSProgress * _Nonnull uploadProgress) {
// xLog(@"%@",uploadProgress);
}success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}else if([method isEqualToString:@"PUT"]){
dataTask = [super PUT:URLString parameters:parameters
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}else if([method isEqualToString:@"PATCH"]){
if (block) {
dataTask = [self PATCH:URLString
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (block) {
block(formData);
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
// xLog(@"%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}else{
dataTask = [super PATCH:URLString parameters:parameters
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}
}else if([method isEqualToString:@"DELETE"]){
dataTask = [super DELETE:URLString parameters:parameters
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
xLog(@"返回 %@ = %@ = %@",responseObject,URLString,method);
[self httpSuccess:success
task:task
responseObject:responseObject
showHUD:showHUD showError:showError];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
[self httpFailure:failure task:task error:error
showHUD:showHUD showError:showError];
}];
}
return dataTask;
}
//PATCH上传文件
-(NSURLSessionDataTask*)PATCH:(NSString *)URLString
parameters:(id)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> _Nonnull))block
progress:(void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(task, error);
}
} else {
if (success) {
success(task, responseObject);
}
}
}];
[task resume];
return task;
}
- (void)httpSuccess:(void (^)(NSURLSessionDataTask *task, id responseObject))success
task:(NSURLSessionDataTask *)task
responseObject:(id)responseObject
showHUD:(BOOL)showHUD
showError:(BOOL)showError
{
[UICommon HidenLoading];
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[app endBackgroundUpdateTask];
if ([responseObject[@"code"] intValue] != HTTP_SUCCESS && showError) {
if([task.currentRequest.URL.absoluteString containsString:@"/location/last"]&&([responseObject[@"code"] intValue] == 5002 || [responseObject[@"code"] intValue] == 5001) ){
[UICommon HidenLoading];
}else{
[self showErrorWithCode:[responseObject[@"code"] intValue] message:responseObject[@"msg"]];
}
}else if (showHUD){
[UICommon HidenLoading];
}
if (success) {
success(task, responseObject);
}
}
- (void)httpFailure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
task:(NSURLSessionDataTask *)task
error:(NSError *)error
showHUD:(BOOL)showHUD
showError:(BOOL)showError{
[UICommon HidenLoading];
xLog(@"请求错误 URL:%@,error = %@",task.currentRequest.URL.absoluteString, error);
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[app endBackgroundUpdateTask];
[UICommon HidenLoading];
if (showError) {
//[UICommon MessageErrorText:error.userInfo[NSLocalizedDescriptionKey]];
[UICommon MessageErrorText:error.userInfo[NSLocalizedDescriptionKey]];
}else if (showHUD){
[UICommon HidenLoading];
}
if (failure) {
failure(task, error);
xLog(@"%@",[[NSString alloc] initWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"]
encoding:NSUTF8StringEncoding]);
}
}
- (void)showErrorWithCode:(int)code message:(NSString *)message{
NSString *msg = @"";
switch (code) {
case HTTP_ERROR_400: msg = @"请求参数错误,错误详情见 msg 参数"; break;
case HTTP_ERROR_401:{
msg = @"accesstoken参数无效";
[User setCurrentUser:nil];
}break;
case HTTP_ERROR_402:{
msg = @"密码已被修改";
[User setCurrentUser:nil];
}break;
case HTTP_ERROR_403: msg = @"业务所需参数校验失败(密码,验证码等无效)"; break;
case HTTP_ERROR_500: msg = @"处理异常,请稍后重试"; break;
case HTTP_ERROR_600: msg = @"触发了平台未定义的业务行为"; break;
case HTTP_ERROR_2000:{
msg = @"账号数据不存在";
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"lastLoginName"];
[[NSUserDefaults standardUserDefaults] synchronize];
[User setCurrentUser:nil];
}break;
case HTTP_ERROR_2001: msg = @"设备数据不存在"; break;
case HTTP_ERROR_2002: msg = @"厂商数据不存在";
// [self invalidSession];
break;
case HTTP_ERROR_2003: msg = @"聊天群不存在"; break;
case HTTP_ERROR_4000: msg = @"该设备已绑定于某一用于,不可再次被绑定"; break;
case HTTP_ERROR_4001: msg = @"该设备已在某一群组中,不能再加入其它群组额"; break;
case HTTP_ERROR_4002: msg = @"该设备不在此群组中,无法对其进行删除"; break;
case HTTP_ERROR_4004: msg = @"该设备未与用户绑定,所以无法进入聊天群组"; break;
case HTTP_ERROR_4005: msg = @"用户还没有使用此手机号注册应用"; break;
case HTTP_ERROR_4006: msg = @"用户不在该设备的联系人中"; break;
case HTTP_ERROR_4007: msg = @"该闹钟已被删除,不在此设备中"; break;
case HTTP_ERROR_4008: msg = @"该免打扰设置已被删除,不在此设备中"; break;
case HTTP_ERROR_4009: msg = @"该照片未找到"; break;
case HTTP_ERROR_4010:{
msg = @"所创建的业务数据因业务场景原因数量已超限(sos号码,闹钟,免打扰)";
// @"contact"
// @"disturbBan"
// @"voiceAlarm"
// if ([task.response.URL.relativePath rangeOfString:str].location != NSNotFound) {
// NSLog(@"这个字符串中有\n");
// }
}break;
case HTTP_ERROR_5001: msg = @"设备未联网,可能当前信号差或关机"; break;
case HTTP_ERROR_5002: msg = @"设备未联网,可能当前信号差"; break;
default:
break;
}
xLog(@"msg ====== %@",msg);
if (message.length > 0)
{
// [UICommon MessageErrorText:message];
[UICommon MessageErrorText:message];
}
else
{
//[UICommon MessageErrorText:msg];
[UICommon MessageErrorText:message];
}
if (!cUser && code != 405) {
[UICommon HidenLoading];
AfterDispatch(1, ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"outLogin"
object:nil];
});
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
// AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (alertView.tag == goHomeTag) {
// [app goHomeViewController];
}else if(alertView.tag == goLoginTag){
// [app goLoginViewController];
}else if(alertView.tag == reQuestTag && _isMust){
// [self POST:reURLString parameters:reParameters success:reSuccess failure:reFailure];
}
}
- (void)invalidSession{
[User setCurrentUser:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadCircleDataView" object:nil];
}
+ (NSString *)getURL:(NSString *)URL objArr:(NSArray *)objArr
{
__block NSString *urlStr = URL;//self.caInterface[@"prefix"];
NSArray *arr = @[@"[openid]",@"[imei]",@"[vendor]",@"[groupid]"];
@try {
[arr enumerateObjectsUsingBlock:^(NSString * _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
__block NSString *str = @"";
NSRange range = [urlStr rangeOfString:key];
if (range.location != NSNotFound) {
if ([key isEqualToString:@"[openid]"]) {
__block User *user = nil;
[objArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[User class]]) {
user = obj;
str = user.openid;
*stop = YES;
}
}];
}else if([key isEqualToString:@"[imei]"] || [key isEqualToString:@"[vendor]"]){
__block Device *device = nil;
[objArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[Device class]]) {
device = obj;
if ([key isEqualToString:@"[vendor]"]) {
str = [NSString stringWithFormat:@"%@",device.vendor];
}else if ([key isEqualToString:@"[imei]"]){
if( device.imei){
str = device.imei;
}
}
*stop = YES;
}
}];
}else if([key isEqualToString:@"[groupid]"]){
__block Circle *circle = nil;
[objArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[Circle class]]) {
circle = obj;
str = circle.groupid;
*stop = YES;
}
}];
}
urlStr = [urlStr stringByReplacingOccurrencesOfString:key withString:str];
}
}];
} @catch (NSException *exception) {
NSLog(@"URL format exception!!!");
}
NSLog(@"get url = %@", urlStr);
return urlStr;
}
- (void)UploadPictureByFileName:(NSString*) fileName
Path:(NSData*) path
success:(void (^)(id responseObject))success
failure:(void (^)(id faiObject))failure
{
NSString *urlString = fileName;
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[app beingBackgroundUpdateTask];
if (!parameters || [parameters isKindOfClass:[NSDictionary class]]) {
parameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
}
if ([User currentUser]) {
[parameters setObject:[User currentUser].openid forKey:@"openid"];
[parameters setObject:[User currentUser].accesstoken forKey:@"accesstoken"];
}
//MARK: 添加app版本号,BundleID,时区,语言等到头部
[self.requestSerializer setValue:kTOKEN_APP_VERSION forHTTPHeaderField:@"Version"];
[self.requestSerializer setValue:kTOKEN_APP_BUNDLEID forHTTPHeaderField:@"BundleId"];
[self.requestSerializer setValue:kTOKEN_APP_LANGUAGE forHTTPHeaderField:@"Accept-Language"];
[self.requestSerializer setValue:kTOKEN_APP_TIMEZONE forHTTPHeaderField:@"Timezone"];
[self POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:path name:@"image" fileName:@"image.jpg" mimeType:@"image/jpg/file"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success)
{
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
NSLog(@"上传错误:%@",error);
}];
}
/// 获取token
- (void)getZYBTokenSuccess:(void (^)(id responseObject))success
failure:(void (^)(id faiObject))failure
{
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
NSString *sign = [NSString stringWithFormat:@"1696929107mmcd50cb395655aaa27d7453af418f002356dc9c21e647443c%@",timeStamp];
[parameters setObject:@"1696929107" forKey:@"appID"];
[parameters setObject:@"mmcd50cb395655aaa2" forKey:@"appKey"];
[parameters setObject:@"client_credentials" forKey:@"grantType"];
[parameters setObject:sign.md5String forKey:@"sign"];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"https://open.paperang.com/api/oauth/token" parameters:parameters error:nil];
request.timeoutInterval = 10.f;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:timeStamp forHTTPHeaderField:@"timeStamp"];
[request setValue:@"client_credentials" forHTTPHeaderField:@"grantType"];
[request setValue:cUser.openid forHTTPHeaderField:@"sign"];
NSURLSessionDataTask*task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSDictionary *dic = responseObject;
if (!error)
{
success(responseObject);
}
else
{
NSLog(@"请求失败error=%@", error);
failure(error);
}
}];
[task resume];
}
/// 获取验证码
- (void)getZYBCode:(NSString *)Token
mobile:(NSString *)mobile
success:(void (^)(id responseObject))success
failure:(void (^)(id faiObject))failure
{
NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:mobile forKey:@"mobile"];
[parameters setObject:[self getVerificationCode] forKey:@"checkCode"];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"https://open.paperang.com/api/ucloud/sms/zwsend" parameters:parameters error:nil];
request.timeoutInterval = 10.f;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"1696929107" forHTTPHeaderField:@"appID"];
[request setValue:@"mmcd50cb395655aaa2" forHTTPHeaderField:@"appKey"];
[request setValue:timeStamp forHTTPHeaderField:@"timeStamp"];
[request setValue:Token forHTTPHeaderField:@"accessToken"];
NSURLSessionDataTask*task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error)
{
success(responseObject);
}
else
{
NSLog(@"请求失败error=%@", error);
failure(error);
}
}];
[task resume];
}
- (NSString *)getVerificationCode
{
NSArray *strArr = [[NSArray alloc]initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",nil] ;
NSMutableString *getStr = [[NSMutableString alloc]initWithCapacity:5];
for(int i = 0; i < 6; i++) //得到六位随机字符,可自己设长度
{
int index = arc4random() % ([strArr count]); //得到数组中随机数的下标
[getStr appendString:[strArr objectAtIndex:index]];
}
NSLog(@"验证码:%@",getStr);
return getStr;
}
@end