LCHTTPRequestSerializer

Objective-C

@interface LCHTTPRequestSerializer : NSObject <LCURLRequestSerialization>

Swift

class LCHTTPRequestSerializer : NSObject, LCURLRequestSerialization

LCHTTPRequestSerializer conforms to the LCURLRequestSerialization & LCURLResponseSerialization protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.

Any request or response serializer dealing with HTTP is encouraged to subclass LCHTTPRequestSerializer in order to ensure consistent default behavior.

  • The string encoding used to serialize parameters. NSUTF8StringEncoding by default.

    Declaration

    Objective-C

    @property (nonatomic) NSStringEncoding stringEncoding;

    Swift

    var stringEncoding: UInt { get set }
  • Whether created requests can use the device’s cellular radio (if present). YES by default.

    See

    NSMutableURLRequest -setAllowsCellularAccess:

    Declaration

    Objective-C

    @property (nonatomic) BOOL allowsCellularAccess;

    Swift

    var allowsCellularAccess: Bool { get set }
  • The cache policy of created requests. NSURLRequestUseProtocolCachePolicy by default.

    See

    NSMutableURLRequest -setCachePolicy:

    Declaration

    Objective-C

    @property (nonatomic) NSURLRequestCachePolicy cachePolicy;

    Swift

    var cachePolicy: NSURLRequest.CachePolicy { get set }
  • Whether created requests should use the default cookie handling. YES by default.

    See

    NSMutableURLRequest -setHTTPShouldHandleCookies:

    Declaration

    Objective-C

    @property (nonatomic) BOOL HTTPShouldHandleCookies;

    Swift

    var httpShouldHandleCookies: Bool { get set }
  • Whether created requests can continue transmitting data before receiving a response from an earlier transmission. NO by default

    See

    NSMutableURLRequest -setHTTPShouldUsePipelining:

    Declaration

    Objective-C

    @property (nonatomic) BOOL HTTPShouldUsePipelining;

    Swift

    var httpShouldUsePipelining: Bool { get set }
  • The network service type for created requests. NSURLNetworkServiceTypeDefault by default.

    See

    NSMutableURLRequest -setNetworkServiceType:

    Declaration

    Objective-C

    @property (nonatomic) NSURLRequestNetworkServiceType networkServiceType;

    Swift

    var networkServiceType: NSURLRequest.NetworkServiceType { get set }
  • The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.

    See

    NSMutableURLRequest -setTimeoutInterval:

    Declaration

    Objective-C

    @property (nonatomic) NSTimeInterval timeoutInterval;

    Swift

    var timeoutInterval: TimeInterval { get set }

Configuring HTTP Request Headers

  • Default HTTP header field values to be applied to serialized requests. By default, these include the following:

    • Accept-Language with the contents of NSLocale +preferredLanguages
    • User-Agent with the contents of various bundle identifiers and OS designations

    @discussion To add or remove default request headers, use setValue:forHTTPHeaderField:.

    Declaration

    Objective-C

    @property (nonatomic, strong, readonly) NSDictionary<NSString *, NSString *> *_Nonnull HTTPRequestHeaders;

    Swift

    var httpRequestHeaders: [String : String] { get }
  • Creates and returns a serializer with default configuration.

    Declaration

    Objective-C

    + (nonnull instancetype)serializer;
  • Sets the value for the HTTP headers set in request objects made by the HTTP client. If nil, removes the existing value for that header.

    Declaration

    Objective-C

    - (void)setValue:(nullable NSString *)value
        forHTTPHeaderField:(nonnull NSString *)field;

    Swift

    func setValue(_ value: String?, forHTTPHeaderField field: String)

    Parameters

    field

    The HTTP header to set a default value for

    value

    The value set as default for the specified header, or nil

  • Returns the value for the HTTP headers set in the request serializer.

    Declaration

    Objective-C

    - (nullable NSString *)valueForHTTPHeaderField:(nonnull NSString *)field;

    Swift

    func value(forHTTPHeaderField field: String) -> String?

    Parameters

    field

    The HTTP header to retrieve the default value for

    Return Value

    The value set as default for the specified header, or nil

  • Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.

    Declaration

    Objective-C

    - (void)setAuthorizationHeaderFieldWithUsername:(nonnull NSString *)username
                                           password:(nonnull NSString *)password;

    Swift

    func setAuthorizationHeaderFieldWithUsername(_ username: String, password: String)

    Parameters

    username

    The HTTP basic auth username

    password

    The HTTP basic auth password

  • Clears any existing value for the “Authorization” HTTP header.

    Declaration

    Objective-C

    - (void)clearAuthorizationHeader;

    Swift

    func clearAuthorizationHeader()

Configuring Query String Parameter Serialization

  • HTTP methods for which serialized requests will encode parameters as a query string. GET, HEAD, and DELETE by default.

    Declaration

    Objective-C

    @property (nonatomic, strong) NSSet<NSString *> *_Nonnull HTTPMethodsEncodingParametersInURI;

    Swift

    var httpMethodsEncodingParametersInURI: Set<String> { get set }
  • Set the method of query string serialization according to one of the pre-defined styles.

    See

    LCHTTPRequestQueryStringSerializationStyle

    Declaration

    Objective-C

    - (void)setQueryStringSerializationWithStyle:
        (LCHTTPRequestQueryStringSerializationStyle)style;

    Swift

    func setQueryStringSerializationWith(_ style: LCHTTPRequestQueryStringSerializationStyle)

    Parameters

    style

    The serialization style.

  • Set the a custom method of query string serialization according to the specified block.

    Declaration

    Objective-C

    - (void)setQueryStringSerializationWithBlock:
        (nullable NSString *_Nonnull (^)(NSURLRequest *_Nonnull, id _Nonnull,
                                         NSError *_Nullable *_Nullable))block;

    Swift

    func setQueryStringSerializationWith(_ block: ((URLRequest, Any, NSErrorPointer) -> String)?)

    Parameters

    block

    A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.

Creating Request Objects

  • Creates an NSMutableURLRequest object with the specified HTTP method and URL string.

    If the HTTP method is GET, HEAD, or DELETE, the parameters will be used to construct a url-encoded query string that is appended to the request’s URL. Otherwise, the parameters will be encoded according to the value of the parameterEncoding property, and set as the request body.

    Declaration

    Objective-C

    - (nonnull NSMutableURLRequest *)
        requestWithMethod:(nonnull NSString *)method
                URLString:(nonnull NSString *)URLString
               parameters:(nullable id)parameters
                    error:(NSError *_Nullable *_Nullable)error;

    Swift

    func request(withMethod method: String, urlString URLString: String, parameters: Any?, error: NSErrorPointer) -> NSMutableURLRequest

    Parameters

    method

    The HTTP method for the request, such as GET, POST, PUT, or DELETE. This parameter must not be nil.

    URLString

    The URL string used to create the request URL.

    parameters

    The parameters to be either set as a query string for GET requests, or the request HTTP body.

    error

    The error that occurred while constructing the request.

    Return Value

    An NSMutableURLRequest object.

  • Creates an NSMutableURLRequest object with the specified HTTP method and URLString, and constructs a multipart/form-data HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2

    Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting NSMutableURLRequest object has an HTTPBodyStream property, so refrain from setting HTTPBodyStream or HTTPBody on this request object, as it will clear out the multipart form body stream.

    Declaration

    Objective-C

    - (nonnull NSMutableURLRequest *)
        multipartFormRequestWithMethod:(nonnull NSString *)method
                             URLString:(nonnull NSString *)URLString
                            parameters:
                                (nullable NSDictionary<NSString *, id> *)parameters
             constructingBodyWithBlock:
                 (nullable void (^)(id<LCMultipartFormData> _Nonnull))block
                                 error:(NSError *_Nullable *_Nullable)error;

    Swift

    func multipartFormRequest(withMethod method: String, urlString URLString: String, parameters: [String : Any]?, constructingBodyWith block: ((LCMultipartFormData) -> Void)?, error: NSErrorPointer) -> NSMutableURLRequest

    Parameters

    method

    The HTTP method for the request. This parameter must not be GET or HEAD, or nil.

    URLString

    The URL string used to create the request URL.

    parameters

    The parameters to be encoded and set in the request HTTP body.

    block

    A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the LCMultipartFormData protocol.

    error

    The error that occurred while constructing the request.

    Return Value

    An NSMutableURLRequest object

  • Creates an NSMutableURLRequest by removing the HTTPBodyStream from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.

    @discussion There is a bug in NSURLSessionTask that causes requests to not send a Content-Length header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:, or any other request with an HTTPBodyStream, writes the contents to the specified file and returns a copy of the original request with the HTTPBodyStream property set to nil. From here, the file can either be passed to LCURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:, or have its contents read into an NSData that’s assigned to the HTTPBody property of the request.

    Declaration

    Objective-C

    - (nonnull NSMutableURLRequest *)
        requestWithMultipartFormRequest:(nonnull NSURLRequest *)request
            writingStreamContentsToFile:(nonnull NSURL *)fileURL
                      completionHandler:
                          (nullable void (^)(NSError *_Nullable))handler;

    Swift

    func request(withMultipartForm request: URLRequest, writingStreamContentsToFile fileURL: URL, completionHandler handler: ((Error?) -> Void)? = nil) -> NSMutableURLRequest

    Parameters

    request

    The multipart form request. The HTTPBodyStream property of request must not be nil.

    fileURL

    The file URL to write multipart form contents to.

    handler

    A handler block to execute.