且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止NSURLSession默认HTTP标头

更新时间:2022-06-19 01:39:38

我怀疑你所要求的是可能的。 NSURLSession(和NSURLConnection)会自动提供多个标题,这就是其中之一。

I doubt what you're asking for is possible. NSURLSession (and NSURLConnection) automatically provide a number of headers, and that's one of them.

也没有合理的理由删除它们。自最初的HTTP / 0.9规范以来,所有这三个标题都已成为规范的一部分( https ://www.w3.org/Protocols/HTTP/HTRQ_Headers.html )。对于没有正确处理它们或完全忽略它们的服务器,绝对没有任何借口。

There's also no valid reason to remove them. All three of those headers have been part of the spec since the original HTTP/0.9 spec (https://www.w3.org/Protocols/HTTP/HTRQ_Headers.html). There's absolutely no excuse for any server not either handling those correctly or ignoring them outright.

如上所述,如果你为这些字段提供了错误的值(默认情况下可能是错的),服务器可能会拒绝给你结果。要解决这个问题,首先要弄清楚服务器实际提供的数据类型,并在Accept标头中指定该值而不是默认值。

With that said, if you provide the wrong value for those fields (and the default may be wrong), the server may refuse to give you results. To solve that problem, first figure out what type of data the server is actually going to provide, and specify that value in the Accept header instead of the default.

例如,您可以将Accept设置为application / json或其他变体之一(什么是正确的JSON内容类型?)如果您期望JSON数据。

For example, you might set Accept to "application/json" or one of the other variants (What is the correct JSON content type?) if you're expecting JSON data.

那就是说,如果你真的必须避免发送这些标头,您可以随时打开套接字,手动构建请求并发送它。假设服务器不需要分块编码,那么很容易做到。 (然而,分块编码是一个惊人的比例,所以如果你的服务器发送回来,你几乎不得不求助于将libcurl添加到你的项目中并使用它来代替发出请求。)

That said, if you really must avoid having those headers sent, you can always open a socket, construct the request manually, and send it. Assuming the server doesn't require chunked encoding, it is pretty easy to do. (Chunked encoding, however, is a horror of Herculean proportions, so if your server sends that back, you'll pretty much have to resort to adding libcurl into your project and using that to make requests instead.)