使用 xcode 获取 HTTP 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6946373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting HTTP headers with xcode
提问by Clinton Walsh
I am trying to get the user agent but when I try and read it, it comes out (null)
我正在尝试获取用户代理,但是当我尝试阅读它时,它出现(空)
NSLog(@"user agent = %@", [request valueForHTTPHeaderField: @"User-Agent"]);
request is an NSURLRequest. So I tried to get the http headers and I don't think there are any. When I use
请求是一个 NSURLRequest。所以我试图获取 http 标头,但我认为没有。当我使用
NSLog(@"http headers = %d", [[req allHTTPHeaderFields] fileSize]);
it prints out zero. req is an NSMutableURLRequest. Does anyone know why this is happening.
它打印出零。req 是一个 NSMutableURLRequest。有谁知道为什么会这样。
This is the method that I am using:
这是我正在使用的方法:
- (BOOL)webView:(UIWebView )webView2 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSMutableURLRequest *req = (NSMutableURLRequest *)request;
NSString *versionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString)kCFBundleVersionKey];
NSLog(@"http headers = %@", [request allHTTPHeaderFields]);
NSLog(@"http headers = %d", [[req allHTTPHeaderFields] fileSize]);
[req setValue:[NSString stringWithFormat:@"myApp/%@ %@", versionString, [request valueForHTTPHeaderField:@"User-Agent"]] forHTTPHeaderField:@"User-Agent"];
NSLog(@"user agent = %@", [request valueForHTTPHeaderField: @"User-Agent"]);}
回答by JohnK
This worked for me:
这对我有用:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"navigator.userAgent = %@", secretAgent);
NSDictionary* headers = [request allHTTPHeaderFields];
NSLog(@"headers: %@",headers);
NSString* ua = [request valueForHTTPHeaderField:@"User-Agent"];
NSLog(@"User-Agent = %@", ua);
}
I don't know why you're looking at filesizewhen you can just look at the headers themselves.
我不知道你为什么要查看filesize当你可以只查看标题本身时。

