網絡層的福爾摩斯:ResponseDetective

fefre 9年前發布 | 9K 次閱讀 iOS開發 移動開發 ResponseDetective

ResponseDetective 是一個非侵入式框架用于攔截任何傳出請求和輸入響應在你的App和你的服務器之間,以達到調試的目的。 

Usage

Incorporating ResponseDetective in your project is very simple – it all comes down to a couple of steps.

Step 1: Register interceptors

You may register as many request, response and error interceptors as you like.

// request
InterceptingProtocol.registerRequestInterceptor(BaseInterceptor())
InterceptingProtocol.registerRequestInterceptor(JSONInterceptor())

// response
InterceptingProtocol.registerResponseInterceptor(BaseInterceptor())
InterceptingProtocol.registerResponseInterceptor(JSONInterceptor())
InterceptingProtocol.registerResponseInterceptor(HTMLInterceptor())

// error
InterceptingProtocol.registerErrorInterceptor(BaseInterceptor())

Step 2: Register the protocol

ForInterceptingProtocolto work, it needs to be added as a middleman between yourNSURLSessionand the Internet. You can do this by registering it in your session'sNSURLSessionConfiguration.protocolClasses.
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses = [InterceptingProtocol.self]

let session = NSURLSession(configuration: configuration)

If you're using Alamofire as your networking framework, integrating ResponseDetective is as easy as initializing yourManagerwithNSURLSessionConfigurationdescribed above.

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses = [InterceptingProtocol.self]

let manager = Alamofire.Manager(configuration: configuration)

Step 3: Profit

Now it's time to perform the actual request.

let request = NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")!)
let task = session.dataTaskWithRequest(request)
task.resume()

Voilà! Now check out your console output.
200 no error

Content-Length: 301
Server: nginx
Content-Type: application/json
Access-Control-Allow-Origin: *
Date: Wed, 08 Jul 2015 13:10:13 GMT
Access-Control-Allow-Credentials: true
Connection: keep-alive

{
  "args" : {

  },
  "headers" : {
    "User-Agent" : "ResponseDetective\/1 CFNetwork\/711.4.6 Darwin\/15.0.0",
    "Accept-Encoding" : "gzip, deflate",
    "Host" : "httpbin.org",
    "Accept-Language" : "en-us",
    "Accept" : "*\/*"
  },
  "origin" : "109.206.223.85",
  "url" : "http:\/\/httpbin.org\/get"
}

項目主頁:http://www.baiduhome.net/lib/view/home/1438007586941

 本文由用戶 fefre 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!