背景
最近在接阿里云的WAF,防火墙会拦截某些请求。被拦截的请求是看不到Headers信息的,只能看到Useragent,所以,应后台需求,自定义Useragent,这样可以更方便从服务器日志定位问题。
准备
当前项目中使用的是Alamofire 进行网络请求。 通过查看源码发现,默认的SessionManager是初始化完成的,不能修改。
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
默认SessionManager 的Useragent也是不可修改的,如下:
open static let defaultHTTPHeaders: HTTPHeaders = {
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
但是可以通过自定义的方法重新初始化一个SessionManager。
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
下面是我的初始化方法:
class MYSessionManager {
open static let `default`: SessionManager = {
let bhUserAgent = "device:xx;version:xx;bundleId:xx;"
var bhHttpHeaders = SessionManager.defaultHTTPHeaders
bhHttpHeaders["User-Agent"] = bhUserAgent
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = bhHttpHeaders
return SessionManager(configuration: configuration)
}()
}
|
请发表评论