我想向服务器发布请求。如果我使用 NSURLSessionDataTask,它工作正常。但在下面,我需要使用 AFNetworking,因为我的整个应用程序都在使用它。但是当我尝试使用 POST 方法在 AFHTTPSessionManager 中访问相同的服务时,它给了我请求超时。
下面是两个代码。
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"BASE URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSString *postString = @"1";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
AFNetworking 套件版本:-
AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"BASE URL"]];
NSDictionary *request = @{@"Content-Type":@"application/json",
@"Accept":@"application/json",
};
NSString *postString = @"1";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[client POST:@"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithHeaders:request body:data];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"%@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",error);
}];
请帮助我以正确的方式实施它。