gpt4 book ai didi

iphone - 如何在 NSURLResponse 中设置 statusCode

转载 作者:太空狗 更新时间:2023-10-30 03:25:54 32 4
gpt4 key购买 nike

我覆盖了 NSURLProtocol 并且需要返回带有特定状态码的 HTTP 响应。 NSHTTPURLResponse 没有 statusCode setter ,所以我尝试用以下方法覆盖它:

@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 吗?谢谢。

最佳答案

这是一个更好的解决方案。

在 iOS 5.0 及更高版本上,您不必再对私有(private) API 或重载 NSHTTPURLResponse 做任何疯狂的事情。

要使用您自己的状态代码和 header 创建一个 NSHTTPUTLResponse,您现在可以简单地使用:

initWithURL:statusCode:HTTPVersion:headerFields:

生成的文档中没有记录,但 实际上存在于 NSURLResponse.h 头文件中,并且还标记为在 OS X 10.7 上可用的公共(public) API和 iOS 5.0。

另请注意,如果您使用 NSURLProtocol 技巧从 UIWebView 进行 XMLHTTPRequest 调用,则需要设置 Access-Control-Allow-Origin 标题适当。否则,XMLHTTPRequest 安全机制将启动,即使您的 NSURLProtocol 将接收并处理该请求,您也无法发回响应。

关于iphone - 如何在 NSURLResponse 中设置 statusCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383746/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com