【问题标题】:NSURLSession request HTTPBody becomes nil in Custom NSURLProtocolNSURLSession 请求 HTTPBody 在 Custom NSURLProtocol 中变为 nil
【发布时间】:2017-05-30 12:01:42
【问题描述】:

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

后续步骤:

  1. 设置标题
  2. 设置 HTTPBody
  3. 使用 NSURLSession 发出 POST 请求。

代码是:

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;
}

提前致谢。

【问题讨论】:

标签: nsurlsession nsurlprotocol


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2014-12-06
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    相关资源
    最近更新 更多