【问题标题】:Can AFNetworking do request like curl -v?AFNetworking 可以请求 curl -v 吗?
【发布时间】:2016-11-07 12:37:05
【问题描述】:

我想制作一个 http-test-tool 来帮助我们发现用户在使用我们的应用程序时遇到的问题,我喜欢使用 curl -v 进行测试。 每一行在调试中都很有用。比如IP、Port、Cert和Headers等等。 iOS平台有没有什么工具可以做到这一点?

curl -v https://stackoverflow.com/
*   Trying 151.101.129.69...
* Connected to stackoverflow.com (151.101.129.69) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate: *.stackexchange.com
* Server certificate: DigiCert SHA2 High Assurance Server CA
* Server certificate: DigiCert High Assurance EV Root CA
> GET / HTTP/1.1
> Host: stackoverflow.com
> User-Agent: curl/7.49.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Cache-Control: public, max-age=60
< Content-Type: text/html; charset=utf-8
< Expires: Mon, 07 Nov 2016 12:33:31 GMT
< Last-Modified: Mon, 07 Nov 2016 12:32:31 GMT
< X-Frame-Options: SAMEORIGIN
< X-Request-Guid: 61dedc6f-13f6-4ea6-970a-a596f885e29c
< Content-Length: 250615
< Accept-Ranges: bytes
< Date: Mon, 07 Nov 2016 12:32:31 GMT
< Via: 1.1 varnish
< Connection: keep-alive
< X-Served-By: cache-hkg6825-HKG
< X-Cache: MISS
< X-Cache-Hits: 0
< X-Timer: S1478521950.280986,VS0,VE949
< Vary: *
< X-DNS-Prefetch-Control: off
< Set-Cookie: prov=ca5856bc-b473-5203-b21e-2b2eb6516fee; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
<
...
...
...

【问题讨论】:

    标签: ios iphone curl afnetworking


    【解决方案1】:

    这是可能的。无论如何,它不像您使用 curl -v 的示例那样在命令行中添加标志那么直接。

    让我们使用AFHTTPSessionManager 上的GET:parameters:success:failure: method 来执行GET 请求。该方法的声明是:

    - (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
                                parameters:(nullable id)parameters 
                                   success:(nullable void (^) (NSURLSessionDataTask *task, id _Nullable responseObject))success
                                   failure:(nullable void (^) (NSURLSessionDataTask *_Nullable task, NSError *error))failure;
    

    这里有两个有趣的块:第一个包含在成功响应的情况下(非常巧妙地命名为success),另一个包含在请求中的failure

    两个块都返回一个类型为 NSURLSessionDataTask 的参数(在失败事件中可以为空,如果是这种情况则没有响应,最有可能在没有互联网连接时发生)。根据继承自NSURLSessionTaskApple Documentation for NSURLSessionDataTask,可以先获取响应对象,然后获取标头。这里是一个简单的example taken from Github

    NSHTTPURLResponse *response = ((NSHTTPURLResponse *)[task response]);
    NSDictionary *headers = [response allHeaderFields];
    // Do something with the headers in the response here...
    

    从这里进一步,看看Symbols for NSURLSessionTask 并采取你需要的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      相关资源
      最近更新 更多