A representation of a URL load request that you use when you need reference semantics or other Foundation-specific behavior.
- iOS 2.0+
- macOS 10.2+
- tvOS 9.0+
- watchOS 2.0+
NSURLRequest encapsulates two essential properties of a load request: the URL to load and the policies used to load it. In addition, for HTTP and HTTPS requests,
URLRequest includes the HTTP method (
POST, and so on) and the HTTP headers. Finally, custom protocols can support custom properties as explained in Custom Protocol Properties.
NSURLRequest only represents information about the request. Use other classes, such as
URLSession, to send the request to a server. See Fetching Website Data into Memory and Uploading Data to a Website for an introduction to these techniques.
The mutable subclass of
Reserved HTTP Headers
The URL Loading System handles various aspects of the HTTP protocol for you (HTTP 1.1 persistent connections, proxies, authentication, and so on). As part of this support, the URL Loading System takes responsibility for certain HTTP headers:
If you set a value for one of these reserved headers, the system may ignore the value you set, or overwrite it with its own value, or simply not send it. Moreover, the exact behavior may change over time. To avoid confusing problems like this, do not set these headers directly.
The URL Loading System sets the
Content-Length header based on whether the request body has a known length:
If so, it uses the identity transfer encoding and sets the
Content-Lengthheader to that known length. You see this when you set the request body to a data object.
If not, it uses the chunked transfer encoding and omits the
Content-Lengthheader. You see this when you set the request body to a stream.
Custom Protocol Properties
If you implement a custom URL protocol by subclassing
URLProtocol, and it needs protocol-specific properties, extend
NSURLRequest with accessor methods for those custom properties. In your accessor methods, call
set to associate property values with the request.