Break apart an HTTP header string that is potentially a quoted, comma separated list as used in entity headers in RFC2616.
160277
def parse_multi_value_header(header_str):
    """"""
    parsed_parts = []
    if header_str:
        parts = header_str.split(',')
        for part in parts:
            match = re.search('\s*(W/)?\"?([^"]*)\"?\s*', part)
            if match is not None:
                parsed_parts.append(match.group(2))
    return parsed_parts
242234
def http_headers
      req_headers = self.reject {|k,v| !k.start_with? "HTTP_" }
      normalized = req_headers.map do |key, value|
        new_key = key.sub("HTTP_",'').split('_').map(&:capitalize).join('-')
        [new_key, value]
      end
      Hash[normalized]
    end
684554
private String parseDestinationHeader( final WebdavRequest req, final WebdavResponse resp )
        throws IOException
    {
        String destinationPath = req.getHeader( "Destination" );

        if ( destinationPath == null )
        {
            resp.sendError( WebdavStatus.SC_BAD_REQUEST );
            return null;
        }

        // Remove url encoding from destination
        destinationPath = RequestUtil.URLDecode( destinationPath, "UTF8" );

        final int protocolIndex = destinationPath.indexOf( "://" );
        if ( protocolIndex >= 0 )
        {
            // if the Destination URL contains the protocol, we can safely
            // trim everything upto the first "/" character after "://"
            final int firstSeparator = destinationPath.indexOf( "/", protocolIndex + 4 );
            if ( firstSeparator < 0 )
            {
                destinationPath = "/";
            }
            else
            {
                destinationPath = destinationPath.substring( firstSeparator );
            }
        }
        else
        {
            final String hostName = req.getServerName();
            if ( ( hostName != null ) && ( destinationPath.startsWith( hostName ) ) )
            {
                destinationPath = destinationPath.substring( hostName.length() );
            }

            final int portIndex = destinationPath.indexOf( ":" );
            if ( portIndex >= 0 )
            {
                destinationPath = destinationPath.substring( portIndex );
            }

            if ( destinationPath.startsWith( ":" ) )
            {
                final int firstSeparator = destinationPath.indexOf( "/" );
                if ( firstSeparator < 0 )
                {
                    destinationPath = "/";
                }
                else
                {
                    destinationPath = destinationPath.substring( firstSeparator );
                }
            }
        }

        // Normalize destination path (remove '.' and' ..')
        destinationPath = normalize( destinationPath );

        final String contextPath = req.getContextPath();
        if ( ( contextPath != null ) && ( destinationPath.startsWith( contextPath ) ) )
        {
            destinationPath = destinationPath.substring( contextPath.length() );
        }

        final String pathInfo = req.getPathInfo();
        if ( pathInfo != null )
        {
            final String servletPath = req.getServicePath();
            if ( ( servletPath != null ) && ( destinationPath.startsWith( servletPath ) ) )
            {
                destinationPath = destinationPath.substring( servletPath.length() );
            }
        }

        return destinationPath;
    }
219299
def parseAcceptHeader(value):
    
    chunks = [chunk.strip() for chunk in value.split(',')]
    accept = []
    for chunk in chunks:
        parts = [s.strip() for s in chunk.split(';')]

        mtype = parts.pop(0)
        if '/' not in mtype:
            # This is not a MIME type, so ignore the bad data
            continue

        main, sub = mtype.split('/', 1)

        for ext in parts:
            if '=' in ext:
                k, v = ext.split('=', 1)
                if k == 'q':
                    try:
                        q = float(v)
                        break
                    except ValueError:
                        # Ignore poorly formed q-values
                        pass
        else:
            q = 1.0

        accept.append((q, main, sub))

    accept.sort()
    accept.reverse()
    return [(main, sub, q) for (q, main, sub) in accept]
1273224
def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=",", quote=True):
        
        res = ""
        ordered = collections.OrderedDict(sorted(authheaders.items()))
        form = '{0}=\"{1}\"' if quote else '{0}={1}'
        if exclude_signature:
            return sep.join([form.format(k, urlquote(str(v), safe='')) for k, v in ordered.items() if k != 'signature'])
        else:
            return sep.join([form.format(k, urlquote(str(v), safe='') if k != 'signature' else str(v)) for k, v in ordered.items()])
251020
def token_and_options(header)
      token = header.to_s.match(/^Token (.*)/) { |m| m[1] }
      if token
        begin
          values = Hash[token.split(',').map do |value|
            value.strip!                      # remove any spaces between commas and values
            key, value = value.split(/\=\"?/) # split key=value pairs
            value.chomp!('"')                 # chomp trailing " in value
            value.gsub!(/\\\"/, '"')          # unescape remaining quotes
            [key, value]
          end]
          [values.delete("token"), values]
        rescue => error
          raise UnprocessableHeader, error
        end
      else
        [nil,{}]
      end
    end
1138739
private void parseHeaders() throws IOException
  {
    _ws.flush();
    
    CharBuffer line = new CharBuffer();

    // Skip blank lines
    int count = 0;
    do {
      line.clear();
      if (! _rs.readln(line)) {
        _isKeepalive = false;
        return;
      }
    } while (line.length() == 0 && ++count < 10);

    if (line.length() == 0) {
      _isKeepalive = false;
      return;
    }

    if (line.startsWith("HTTP/1.1 100")) {
      count = 100;
      do {
        line.clear();
        if (! _rs.readln(line)) {
          _isKeepalive = false;
          return;
        }
      } while (line.length() != 0 && count-- > 0);
      
      count = 100;
      do {
        line.clear();
        if (! _rs.readln(line)) {
          _isKeepalive = false;
          return;
        }
      } while (line.length() == 0 && count-- > 0);
    }

    if (line.length() == 0) {
      _isKeepalive = false;
      return;
    }

    int i = 0;
    for (i = 0; i < line.length() && line.charAt(i) != ' '; i++) {
    }
    
    for (; i < line.length() && line.charAt(i) == ' '; i++) {
    }
    
    int status = 0;
    for (; i < line.length(); i++) {
      char ch = line.charAt(i);
      if (ch >= '0' && ch <= '9')
        status = 10 * status + ch - '0';
      else
        break;
    }

    if (status != 200)
      _isKeepalive = false;
    else if (! line.startsWith("HTTP/1.1 "))
      _isKeepalive = false;

    _attributes.put("status", String.valueOf(status));
    _attributes.put("status-message", line.toString());

    CharBuffer key = new CharBuffer();
    while (true) {
      line.clear();
      if (! _rs.readln(line) || line.length() == 0)
          break;

      int lineLength = line.length();
      
      for (i = 0;
           i < lineLength && Character.isWhitespace(line.charAt(i));
           i++) {
      }

      key.clear();
      for (;
           i < lineLength && ! Character.isWhitespace(line.charAt(i))
             && line.charAt(i) != ':';
           i++) {
        key.append((char) line.charAt(i));
      }

      for (;
           i < lineLength && Character.isWhitespace(line.charAt(i));
           i++) {
      }

      if (key.length() == 0 || lineLength <= i || line.charAt(i) != ':')
        continue;

      for (i++;
           i < lineLength && Character.isWhitespace(line.charAt(i));
           i++) {
      }

      key.toLowerCase();
      String value = line.substring(i);

      if (log.isLoggable(Level.FINE))
        log.fine(key + ": " + value);
      
      if (key.matchesIgnoreCase("content-length")) {
        _contentLength = Integer.parseInt(value.trim());
      }
      else if (key.matchesIgnoreCase("connection")
               && value.equalsIgnoreCase("close")) {
        _isKeepalive = false;
      }
      else if (key.matchesIgnoreCase("transfer-encoding")
               && value.equalsIgnoreCase("chunked")) {
        
        _isChunked = true;
        _chunkLength = 0;
      }

      String keyString = key.toLowerCase().toString();
      
      String oldValue = (String) _attributes.put(keyString, value);

      if (oldValue != null) {
        value = oldValue + '\n' + value;
      }
      
      _attributes.put(keyString, value);
    }
  }
919321
def parse_header(cls, value='*/*'):
        """"""
        yield from sorted((
            cls.from_string(token.strip())
            for token in value.split(',')
            if token.strip()
        ), reverse=True)
580526
private Object toLogString(HttpRequestMessage httpRequest) {
        StringBuilder b = new StringBuilder();
        b.append(httpRequest.getRequestURI()).append('\n');
        final Map<String,List<String>> headers = httpRequest.getHeaders();
        for ( String h: headers.keySet()) {
            b.append(h).append(':').append(' ').append(headers.get(h)).append('\n');
        }
        return b.toString();
    }
298669
function parse (headers) {
  if (headers.slice(0,4).toLowerCase() == 'http') {
    var newlineIndex = headers.indexOf('\r\n');
    headers = headers.slice(newlineIndex + 2);
  }
  return parseHeaders(headers);
}
457749
def parse(self, charset=None, headers=None):
        

        if headers:
            self.headers = headers
        else:
            # Parse headers only from last response
            # There could be multiple responses in `self.head`
            # in case of 301/302 redirect
            # Separate responses
            if self.head:
                responses = self.head.rsplit(b'\nHTTP/', 1)
                # Cut off the 'HTTP/*' line from the last response
                _, response = responses[-1].split(b'\n', 1)
                response = response.decode('utf-8', 'ignore')
            else:
                response = u''
            if six.PY2:
                # email_from_string does not work with unicode input
                response = response.encode('utf-8')
            self.headers = email.message_from_string(response)

        if charset is None:
            if isinstance(self.body, six.text_type):
                self.charset = 'utf-8'
            else:
                self.detect_charset()
        else:
            self.charset = charset.lower()

        self._unicode_body = None
1138077
private String parseDestinationHeader(HttpServletRequest req) {

        // Parsing destination header
        String destinationPath = req.getHeader(HEADER_DESTINATION);

        if (destinationPath == null) {
            return null;
        }

        // Remove url encoding from destination
        destinationPath = CmsEncoder.decode(destinationPath, "UTF8");

        int protocolIndex = destinationPath.indexOf("://");
        if (protocolIndex >= 0) {

            // if the Destination URL contains the protocol, we can safely
            // trim everything upto the first "/" character after "://"
            int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4);
            if (firstSeparator < 0) {
                destinationPath = "/";
            } else {
                destinationPath = destinationPath.substring(firstSeparator);
            }
        } else {
            String hostName = req.getServerName();
            if ((hostName != null) && (destinationPath.startsWith(hostName))) {
                destinationPath = destinationPath.substring(hostName.length());
            }

            int portIndex = destinationPath.indexOf(":");
            if (portIndex >= 0) {
                destinationPath = destinationPath.substring(portIndex);
            }

            if (destinationPath.startsWith(":")) {
                int firstSeparator = destinationPath.indexOf("/");
                if (firstSeparator < 0) {
                    destinationPath = "/";
                } else {
                    destinationPath = destinationPath.substring(firstSeparator);
                }
            }
        }

        // Normalise destination path (remove '.' and '..')
        destinationPath = normalize(destinationPath);

        String contextPath = req.getContextPath();
        if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
            destinationPath = destinationPath.substring(contextPath.length());
        }

        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            String servletPath = req.getServletPath();
            if ((servletPath != null) && (destinationPath.startsWith(servletPath))) {
                destinationPath = destinationPath.substring(servletPath.length());
            }
        }

        return destinationPath;
    }
843242
def str_to_hash
        client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first
        if client.nil?
          @errors << "client is not registered"
        end
        client.nil? ? "" : client.secret + @request_uri.gsub( /\?.*/, "" ) + @http_headers[@@header_timestamp]
      end
37892
function (requestV1) {
        if (!requestV1) { return; }
        if (requestV1.headers && _.isEmpty(requestV1.headerData)) {
            // this converts a newline concatenated string of headers to an array, so there are no descriptions
            return v1Common.parseHeaders(requestV1.headers, true);
        }

        // however, if non empty headerData already exists, sanitize it.
        return normalizeEntities(requestV1.headerData, this.options);
    }
107438
def parse_email_headers(s)
		keys={}
		match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/)
		if match != 0
			keys[:data] = s
		else
			keys[:data] = $'
			headers = $1
			headers.split("\n").each do |l| 
# Fails if there are other ':' characters.
#				k, v = l.split(':')
				k, v = l.split(':', 2)
				k, v = normalize_key_and_value(k, v)
				k = k.to_sym
#				puts "K = #{k}, V=#{v}"
				keys[k] = v
			end
		end
		keys
	end
482270
def raw
      headers = http_headers.map { |k, v| "#{k}: #{v}\r\n" }.join
      format "%s %s %s\r\n%s\r\n%s", request_method.upcase, fullpath, env["SERVER_PROTOCOL"], headers, body_string
    end
974797
void parseNextResponse() throws IOException {
    contentId++;

    // Extract the outer headers.
    String line;
    while ((line = readLine()) != null && !line.equals("")) {
      // Do nothing.
    }

    // Extract the status code.
    String statusLine = readLine();
    String[] statusParts = statusLine.split(" ");
    int statusCode = Integer.parseInt(statusParts[1]);

    // Extract and store the inner headers.
    // TODO(rmistry): Handle inner headers that span multiple lines. More details here:
    // http://tools.ietf.org/html/rfc2616#section-2.2
    List<String> headerNames = new ArrayList<String>();
    List<String> headerValues = new ArrayList<String>();
    long contentLength = -1L;
    while ((line = readLine()) != null && !line.equals("")) {
      String[] headerParts = line.split(": ", 2);
      String headerName = headerParts[0];
      String headerValue = headerParts[1];
      headerNames.add(headerName);
      headerValues.add(headerValue);
      if ("Content-Length".equalsIgnoreCase(headerName.trim())) {
          contentLength = Long.parseLong(headerValue);
      }
    }

    InputStream body;
    if (contentLength == -1) {
      // This isn't very efficient, but most respectable servers should set the Content-Length
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while ((line = readRawLine()) != null && !line.startsWith(boundary)) {
        // Convert characters back to bytes:
        buffer.write(line.getBytes("ISO-8859-1"));
      }

      // Remove CRLF that separates body from boundary token
      body = trimCrlf(buffer.toByteArray());

      // Remove CRLF from the boundary token (to match readLine)
      line = trimCrlf(line);
    } else {
      body = new FilterInputStream(ByteStreams.limit(inputStream, contentLength)) {
        @Override
        public void close() {
          // Don't allow the parser to close the underlying stream
        }
      };
    }

    HttpResponse response =
        getFakeResponse(statusCode, body, headerNames, headerValues);

    parseAndCallback(requestInfos.get(contentId - 1), statusCode, response);

    // Consume any bytes that were not consumed by the parser
    while (body.skip(contentLength) > 0 || body.read() != -1) {
    }

    if (contentLength != -1) {
      line = readLine();
    } else {
      // The line was already read
    }
    // Consume any blank lines that follow the response (not included in Content-Length)
    while ((line != null) && (line.length() == 0)) {
      line = readLine();
    }

    checkForFinalBoundary(line);
  }