• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift自定义Useragent

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

背景

最近在接阿里云的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)
    }()
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift - Core Graphics绘图框架详解1(绘制线条)发布时间:2022-07-13
下一篇:
Linux 下使用 Swift MQTT发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap