NSURLSession请求HTTPBody在自定义NSURLProtocol中变为nil

时间:2017-05-30 12:01:42

标签: nsurlsession nsurlprotocol

在我的应用程序中,我使用NSURLSession执行POST。

遵循的步骤:

  1. 设置标题
  2. 设置HTTPBody
  3. 使用NSURLSession发出POST请求。
  4. 代码是:

    NSDictionary *parameters = @{ @"searchTerm": @"shampoo", @"sort": @"Most Reviewed" };
    NSError *error = nil;
    NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"SomeURL"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setAllHTTPHeaderFields:headers];
    request.HTTPBody = postData;
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        NSLog(@"%@", error);
                                                    } else {
    
                                                        NSLog(@"Pass");
                                                    }
                                                }];
    [dataTask resume];
    

    现在在自定义NSURLProtocol类中:

    (BOOL)canInitWithRequest:(NSURLRequest *)request {
    
        if ([request.HTTPMethod isEqualToString:@"POST"]) {
        //here request.HTTPMethod is coming nil
        //Whereas my requirement is to get request.HTTPMethod which got     request parameter.
            return YES;
        }
    
        return NO;
    }
    

    提前致谢。

1 个答案:

答案 0 :(得分:0)

IIRC,正文数据对象在到达您之前会被URL加载系统透明地转换为流式正文。如果您需要读取数据: 打开HTTPBodyStream对象 从中读取身体数据 有一个警告:流可能无法倒带,因此不要将该请求对象传递给以后需要访问主体的任何其他代码。不幸的是,也没有请求新主体流的机制(有关其他限制,请参阅Apple网站上CustomHTTPProtocol示例代码项目的README文件)。

相关问题