-->

What is the difference between HTTP parameters and

2020-08-13 07:18发布

问题:

I read this question but it didn't answer my question.

To me Headers and Parameters are both dictionaries with the difference that headers is [String : String] while Parameters is [String : AnyObject]? and so if your parameters are also Strings then you could send them within the headers (while using a 'x-' prefix to signify they aren't standard headers) which is a common but not good practice.

  • Is that correct?
  • Are there other difference between headers and parameters?
  • What kind of other non-String types would you be sending using parameters?

Alamofire Request method

public func request(
        method: Method,
        _ URLString: URLStringConvertible,
          parameters: [String: AnyObject]? = nil,
          encoding: ParameterEncoding = .URL,
          headers: [String: String]? = nil)
        -> Request
    {
        return Manager.sharedInstance.request(
            method,
            URLString,
            parameters: parameters,
            encoding: encoding,
            headers: headers
        )
    }

As an example I have seen people passing ["x-ios-version" : UIDevice.currentDevice().systemVersion] or build versions through headers

回答1:

Here is the list of differences:

  1. They are designed for different purposes. Headers carry meta info, parameters carry actual data.

  2. Server side will automatically un-escape/decode parameter names/values. This does not apply for header names/values.

  3. Header names/values need to be manually escaped/encoded at client side and be manually un-escaped/decoded at server side. Base64 encoding or percent escape is often used.

  4. Parameters can be seen by end-users (query parameters) on URL but headers are hidden to end-users.



回答2:

From discussion with Rob in chat:

The criteria is that if it's information about the request or about the client, then the header is appropriate.
But if it's the content of the request itself (e.g. what you are requesting from the server, some details that identify the item to be returned, some details to be saved on the web server, etc.), then it's a parameter.

As an example:

Parameter
Let's say you're requesting an image for a product. The product id may be one parameter. The image size (thumbnail vs full size) might be another parameter. The product id and requested image size are examples of "some detail" (or parameter) being supplied as part of the content of a request.

Header
But things like the request is JSON or x-www-form-urlencoded are not the content of the request, but rather information about the request (esp since that's necessary for web service to know how to parse the body of the request). That's why it's a header.