前段时间项目中,在数据请求的时候,有用到请求头,上传vo实体作为body,特此封装了一个post相关的数据请求(get同理),Mark一下。
//POST,设置body包含code
- (void)postRequestWithBodyUrl:(NSString *)url
params:(id)params
success:(SuccessBlock)success
failureCode:(FailureBlockCode)failure
{
NSLog(@"请求路径: %@ \n\t请求参数: %@", url, params?:@"nil");
NSString *requestURL=[HostName stringByAppendingString:url];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestURL parameters:nil error:nil];
request.timeoutInterval= 10;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:KToken forHTTPHeaderField:@"token"];
[request setValue:Kplatform forHTTPHeaderField:@"platform"];
[request setValue:kappVersion forHTTPHeaderField:@"appVersion"];
NSData *body =[params dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:body];
if ([CommonUtils checkNet]) {
[[self.sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger responseStatusCode = [httpResponse statusCode];
NSInteger code = [[responseObject objectForKey:@"code"] integerValue];
if (0 == code) {
success(responseObject,code);
}else {
failure(nil, responseObject[@"msg"],code);
}
NSLog(@"请求路径:%@\n\t返回结果: %@", response.URL, responseObject);
}]resume];
}
else{
NSError *error;
failure(error , @"服务器连接失败",10001);
}
}