使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:39:04  来源:igfitidea点击:

Getting HTTP headers with xcode

xcodehttpheaderuser-agentnsurlrequest

提问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当你可以只查看标题本身时。

Cf. https://stackoverflow.com/a/19184414/1431728

参见 https://stackoverflow.com/a/19184414/1431728

回答by highlycaffeinated

You don't have any headers in your request object because you haven't added any. If you want to specify the User-Agentheader, you need to add it yourself, as outlined here.

您的请求对象中没有任何标头,因为您尚未添加任何标头。如果你想指定的User-Agent头,你需要将它自己添加,如概述这里