我覆盖了 NSURLProtocol 并且需要返回带有特定状态码的 HTTP 响应。NSHTTPURLResponse 没有 statusCode 设置器,所以我尝试用以下方法覆盖它:
@interface MyHTTPURLResponse : NSHTTPURLResponse {}
@implementation MyHTTPURLResponse
- (NSInteger)statusCode {
return 200; //stub code
}
@end
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];
}
}
但是这种方法不起作用,在 NSURLProtocol 中创建的响应在网页上总是带有 statusCode = 0。同时,由 NSURLConnection 从网络返回的响应具有正常的预期状态码。
任何人都可以请教如何为创建的 NSURLResponse 显式设置 statusCode 吗?谢谢。