afnetworking 3.0 How to POST with headers and HTTP Body

一般请求的话是这样

     AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    [session POST:@"" parameters:@"" progress:nil success:nil failure:nil];

但是今天遇到个不管怎么样parameters都传不到服务器那边,而后台那边给我的解释是传输用[request setHTTPBody:data];
而 afn 2.0 是这样的

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
   options:0
     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"Reply JSON: %@", responseObject);

    }
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);

}];
[operation start];

但是3.0弃用了AFHTTPRequestOperationManager,那么怎么才能用呢?
1.用系统NSURLConnection 请求

      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"url"]];
        [request setHTTPBody:data];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
        NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    
        if (theConnection) {
            NSLog(@"connected");
            receivedData=[[NSMutableData alloc]init];
        } else {
    
            NSLog(@"not connected");
        }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"response: %@",responseString);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %lu data",(unsigned long)[receivedData length]);
    NSString* responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"response: %@",responseString);
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];
    NSLog(@"%@",res);
}

2.用不习惯系统没关系,其实afn3.0 也有提供api给我们调用,但是这个是我一直没接触过的AFURLSessionManager。

 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"url" parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:da];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"Reply JSON: %@", responseObject);
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        }
    }] resume];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • AFN什么是AFN全称是AFNetworking,是对NSURLConnection、NSURLSession的一...
    醉叶惜秋阅读 1,258评论 0 0
  • 网络解析:AFNnetworking详解 一、什么事AFN□在iOS开发中,使用比较广泛□全称是AFNetwork...
    Bo_cake阅读 904评论 0 1
  • 访问网络的基本流程:5点 HTTP协议 2.通信过程 --------------请求的方法-----get 和 ...
    光明程辉阅读 1,034评论 0 2
  • 同步请求和异步请求- 同步请求:阻塞式请求,会导致用户体验的中断- 异步请求:非阻塞式请求,不中断用户体验,百度地...
    WangDavid阅读 626评论 0 0
  • 在上一篇关于朋友圈的文中,我写了一篇关于如何在朋友圈打造自己的个人品牌的文章。 然而,就像纸上谈兵一样,我并没有做...
    小筱茶籽阅读 578评论 0 2