我正在尝试将我的一个Android应用程序移植到Mac OS X上本地工作。
对于应用程序的初始化,它需要连接到服务器并只读取服务器响应的标头。服务器(第三方服务器)将响应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];
然而,这仍会下载整个页面。
有人能指出我正确的方向吗?
答案 0 :(得分:1)
让我们看看如果我们点击该网址会发生什么。
› 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
发出了www.grooveshark.com
个请求,然后是GET
到grooveshark.com
。