我重写NSURLProtocol并需要返回具有特定statusCode的HTTP响应.NSHTTPURLResponse没有statusCode setter,所以我尝试用以下方法覆盖它:
@interface MyHTTPURLResponse : NSHTTPURLResponse {}
@implementation MyHTTPURLResponse
- (NSInteger)statusCode {
return 200; //stub code
}
@end
Run Code Online (Sandbox Code Playgroud)
重写的NSURLProtocol的startLoading方法如下所示:
-(void)startLoading
{
NSString *url = [[[self request] URL] absoluteString];
if([url isEqualToString:SPECIFIC_URL]){
MyURLResponse *response = [[MyURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://fakeUrl"]
MIMEType:@"text/plain"
expectedContentLength:0 textEncodingName:nil];
[[self client] URLProtocol:self
didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:[@"Fake response string"
dataUsingEncoding:NSASCIIStringEncoding]];
[[self client] URLProtocolDidFinishLoading:self];
[response release];
}
else{
[NSURLConnection connectionWithRequest:[self request] delegate:self];
}
}
Run Code Online (Sandbox Code Playgroud)
但是这种方法不起作用,在NSURLProtocol中创建的响应总是在网页上使用statusCode = 0.同时,NSURLConnection从网络返回的响应具有正常的预期statusCodes.
任何人都可以请求有关如何为创建的NSURLResponse显式设置statusCode的想法?感谢名单.