NSURLSession是否自动发送用户代理 [英] does NSURLSession send user-agent automatically
问题描述
当用户WatchKit 2.0,iOS 9.0时,NSURLSession是否自动发送用户代理? 有没有办法在WatchKit应用程序中对此进行验证?
Does NSURLSession send user-agent automatically when user WatchKit 2.0, iOS 9.0? Is there a way to verify this within the WatchKit app?
推荐答案
是的,将自动提供用户代理作为默认会话配置的一部分.
Yes, a user agent is automatically provided as part of the default session configuration.
默认的NSURLSession
请求标头User-Agent
字段包括watchOS应用程序扩展的捆绑包名称(CFBundleName
)和内部版本号(CFBundleVersion
):
The default NSURLSession
request header User-Agent
field includes the Bundle Name (CFBundleName
) and the Build Number (CFBundleVersion
) of your watchOS app extension:
$(CFBundleName)/$(CFBundleVersion) CFNetwork/808.3 Darwin/16.3.0
请注意,不包括您应用的版本号(CFBundleShortVersionString
). (请参见技术说明TN2420:版本号和内部版本 了解更多信息.)
Notice that your app's Version Number (CFBundleShortVersionString
) isn't included. (See Technical Note TN2420: Version Numbers and Build Numbers for more info.)
例如,对于内部版本号为1的产品"Foo",您的用户代理应为:
For example, for product "Foo" with the Build Number 1, your user agent would be:
Foo%20WatchKit%20Extension/1 CFNetwork/808.3 Darwin/16.3.0
如何验证?
我认为您的应用程序中没有方法可以检查默认的用户代理字段,因为它是nil
(除非您将其设置为自定义值).
How to Verify?
I don't think there's a way within your app to examine the default user agent field, as it's nil
(unless you've set it to a custom value).
但是,您可以使用netcat来检查模拟器发送的请求.
But, you could use netcat to examine requests sent by the Simulator.
-
在终端中运行
nc -l 5678
,以使netcat侦听端口5678
Run
nc -l 5678
in Terminal to have netcat listen to requests sent tolocalhost
on port5678
在应用程序的Info.plist
文件中,添加应用程序传输安全设置"字典,并将允许任意加载"键设置为YES
In your app's Info.plist
file, add the App Transport Security Settings dictionary with the Allow Arbitrary Loads key set to YES
将以下代码添加到application(_:didFinishLaunchingWithOptions:)
let url = URL(string: "http://localhost:5678/")!
URLSession.shared.dataTask(with: url) { (data, response, error) in
let body = String(data: data!, encoding: .utf8)!
print("body: \(body)")
}.resume()
return true
在模拟器中运行您的应用,然后在终端中查看netcat的输出
Run your app in the Simulator and see what netcat outputs in Terminal
如果您的隐私无关紧要,则可以使用 user-agent.me 之类的服务进行测试在您的设备上.
If your privacy is of no concern, you could use a service like user-agent.me to test on your device.
-
用
user-agent.me
在设备上运行您的应用
检查Xcode的控制台输出
Examine Xcode's Console output
完成验证后,请记住撤消上述所有更改.
When you're done verifying, remember to undo all of the changes above.
这篇关于NSURLSession是否自动发送用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!