0

我正在尝试移植我的一个 Android 应用程序以在 Mac OS X 上本地工作。

对于应用程序的初始化,它需要连接到服务器并仅读取服务器响应的标头。服务器(第 3 方服务器)将响应 82274 字节的数据,但对我来说唯一有用的数据是标题;具体来说,我需要读取会话 cookie 并检索它的值。这意味着所有其他数据都是冗余的。

通过谷歌搜索,唯一有效的响应如下:

// Create the request.
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.grooveshark.com/"]];
    [theRequest setHTTPMethod:@"HEAD"];
    [theRequest setValue:@"MySpecialUserAgent/1.0" forHTTPHeaderField:@"User-Agent"];
    [theRequest setTimeoutInterval:15.0];
    [theRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];

但是,这仍然会下载整个页面。

谁能指出我正确的方向?

4

1 回答 1

1

让我们看看如果我们点击那个 URL 会发生什么。

› curl -v -X HEAD http://www.grooveshark.com
* About to connect() to www.grooveshark.com port 80 (#0)
*   Trying 8.20.213.76...
* connected
* Connected to www.grooveshark.com (8.20.213.76) port 80 (#0)
> HEAD / HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: www.grooveshark.com
> Accept: */*
> 
< HTTP/1.1 301 Moved Permanently
< Server: richhickey
< Date: Sat, 15 Dec 2012 20:27:38 GMT
< Content-Type: text/html; charset=UTF-8
< Connection: close
< Location: http://grooveshark.com
< Vary: Accept-Encoding
< X-Hostname: rhl081
< X-Hostname: rhl081
< 
* Closing connection #0

所以www.grooveshark.com重定向到grooveshark.com. 让我们看看该页面HEAD是否正确处理请求。

› curl -v -X HEAD http://grooveshark.com    
* About to connect() to grooveshark.com port 80 (#0)
*   Trying 8.20.213.76...
* connected
* Connected to grooveshark.com (8.20.213.76) port 80 (#0)
> HEAD / HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: grooveshark.com
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: richhickey
< Date: Sat, 15 Dec 2012 20:28:06 GMT
< Content-Type: text/html; charset=UTF-8
< Connection: close
< Vary: Accept-Encoding
< Set-Cookie: PHPSESSID=844a5e6bdd6d84a97afd8f42faf4eb95; expires=Sat, 22-Dec-2012 20:28:06 GMT; path=/; domain=.grooveshark.com
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Vary: Accept-Encoding
< X-Hostname: rhl061
< Set-Cookie: ismobile=no;domain=.grooveshark.com;path=/
< X-country: US
< 
* Closing connection #0

这看起来不错。我怀疑您的请求在遵循该重定向时会退回到 GET。看起来 Chris Suter 遇到了同样的事情并给出了一个示例解决方案:http ://sutes.co.uk/2009/12/nsurlconnection-using-head-met.html

将来您可能想尝试通过本地代理运行您的请求,以便您可以看到它们正在运行。这可能会表明您发出HEAD请求 towww.grooveshark.com后跟 a GETto grooveshark.com

于 2012-12-15T20:35:24.833 回答