我项目里网络请求的Content-Type是application/octet-stream;charset=utf-8。
这种方式跟application/json的不一样,请求参数是二进制的数据流形式的,必须放到body里面去请求。所以问题来了,之前项目用的AFNetworking是2.5.+ 的,现在更新了AFNetworking到3.0+,发现之前的网络请求的AFHTTPRequestOperation被废弃了。现在用AFHTTPSessionManager代替了。不知道怎么设置Header??
AFNetworking 2.0+ 设置请求头
NSMutableURLRequest *jsonRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURLURLWithString:request.stringOfApiURLString]];
jsonRequest.HTTPMethod= @"POST";
NSMutableData *postBody = [NSMutableData data];intmsgid = request.msgid;
NSData *dataMsgid = [NSData dataWithBytes:&msgid length:4];
[postBody appendData:dataMsgid];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:jsonRequest];
[op.securityPolicysetAllowInvalidCertificates:YES];
[op.securityPolicysetValidatesDomainName:NO];
[op.securityPolicysetValidatesCertificateChain:NO];
op.responseSerializer= [AFHTTPResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,idresponseObj){//处理数据}
} failure:^(AFHTTPRequestOperation *operation,NSError*error) {if(failure) {
failure(error);NSString*str = [[NSStringalloc]initWithData:operation.responseObjectencoding:NSUTF8StringEncoding];NSLog(@"--- request error %@",str);
}
}];
[[NSOperationQueue mainQueue] addOperation:op];
AFNetworking 3.0+ 设置请求头
NSMutableURLRequest *jsonRequest =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:request.stringOfApiURLString]];
jsonRequest.HTTPMethod = @"POST";
NSMutableData *postBody = [NSMutableData data];
int msgid = request.msgid;
NSData *dataMsgid = [NSData dataWithBytes:&msgid length:4];
[postBody appendData:dataMsgid];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setSecurityPolicy:[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setStringEncoding:NSUTF8StringEncoding];
// [requestSerializer setTimeoutInterval:10]; [requestSerializer setValue:@"application/octet-stream;charset=utf-8"forHTTPHeaderField:@"Content-Type"];
[manager setRequestSerializer:requestSerializer];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
[responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/octet-stream",nil]];
[manager setResponseSerializer:responseSerializer];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//处理你的数据
}
}else{
NSLog(@"Error: %@, %@, %@",error, response, responseObject);
}
}] resume];