如何在nsurlresponse中设置状态代码
-
10-10-2019 - |
题
我覆盖了NSURLProtocol,需要用特定的状态代码返回HTTP响应。 nshttpurlresponse没有状态代码设置器,因此我试图用:
@interface MyHTTPURLResponse : NSHTTPURLResponse {}
@implementation MyHTTPURLResponse
- (NSInteger)statusCode {
return 200; //stub code
}
@end
NsurlProtocol的覆盖起始加载方法看起来像这样:
-(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明确设置状态代码吗? thanx。
解决方案
我已经使用以下代码实现了自定义初始方法:
NSInteger statusCode = 200;
id headerFields = nil;
double requestTime = 1;
SEL selector = NSSelectorFromString(@"initWithURL:statusCode:headerFields:requestTime:");
NSMethodSignature *signature = [self methodSignatureForSelector:selector];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:signature];
[inv setTarget:self];
[inv setSelector:selector];
[inv setArgument:&URL atIndex:2];
[inv setArgument:&statusCode atIndex:3];
[inv setArgument:&headerFields atIndex:4];
[inv setArgument:&requestTime atIndex:5];
[inv invoke];
其他提示
这是一个更好的解决方案。
在iOS 5.0及以上,您不必对私人API或超载做任何疯狂的事情 NSHTTPURLResponse
再过了。
创建一个 NSHTTPUTLResponse
使用您自己的状态代码和标题,您现在可以简单地使用:
initWithURL:statusCode:HTTPVersion:headerFields:
它没有在生成的文档中记录到 是 实际存在于 NSURLResponse.h
标题文件,还标记为OS X 10.7和iOS 5.0上的公共API。
另请注意,如果您正在使用 NSURLProtocol
诀窍 XMLHTTPRequest
来自a的电话 UIWebView
, ,您需要设置 Access-Control-Allow-Origin
标题适当。否则 XMLHTTPRequest
安全启动,即使您 NSURLProtocol
将接收和处理请求,您将无法回复。
您仅从urlresponse获取状态代码。无需明确设置: -
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"ResponseString:%@",responseString);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int statusCode = [httpResponse statusCode];
NSLog(@"%d",statusCode);
不隶属于 StackOverflow