Java parse http headers

Class HttpHeaders

An HttpHeaders is not typically created directly, but rather returned from an HttpRequest or an HttpResponse . Specific HTTP headers can be set for a request through one of the request builder’s headers methods.

The methods of this class ( that accept a String header name ), and the Map returned by the map method, operate without regard to case when retrieving the header value(s).

An HTTP header name may appear more than once in the HTTP protocol. As such, headers are represented as a name and a list of values. Each occurrence of a header value is added verbatim, to the appropriate header name list, without interpreting its value. In particular, HttpHeaders does not perform any splitting or joining of comma separated header value strings. The order of elements in a header value list is preserved when building a request. For responses, the order of elements in a header value list is the order in which they were received. The Map returned by the map method, however, does not provide any guarantee with regard to the ordering of its entries.

Читайте также:  Radio guru ru index html

HttpHeaders instances are immutable.

Method Summary

Returns an Optional containing the first header string value of the given named (and possibly multi-valued) header.

Methods declared in class java.lang.Object

Method Details

firstValue

Returns an Optional containing the first header string value of the given named (and possibly multi-valued) header. If the header is not present, then the returned Optional is empty.

firstValueAsLong

Returns an OptionalLong containing the first header string value of the named header field. If the header is not present, then the Optional is empty. If the header is present but contains a value that does not parse as a Long value, then an exception is thrown.

allValues

Returns an unmodifiable List of all of the header string values of the given named header. Always returns a List, which may be empty if the header is not present.

map

equals

Tests this HTTP headers instance for equality with the given object. If the given object is not an HttpHeaders then this method returns false . Two HTTP headers are equal if each of their corresponding maps are equal. This method satisfies the general contract of the Object.equals method.

hashCode

Computes a hash code for this HTTP headers instance. The hash code is based upon the components of the HTTP headers map , and satisfies the general contract of the Object.hashCode method.

toString

of

Returns an HTTP headers from the given map. The given map’s key represents the header name, and its value the list of string header values for that header name. An HTTP header name may appear more than once in the HTTP protocol. Such, multi-valued, headers must be represented by a single entry in the given map, whose entry value is a list that represents the multiple header string values. Leading and trailing whitespaces are removed from all string values retrieved from the given map and its lists before processing. Only headers that, after filtering, contain at least one, possibly empty string, value will be added to the HTTP headers.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Which java libraries do http accept header parsing

Read the first line [Request-Line = Method SP Request-URI SP HTTP-Version CRLF] Read the request header line by line till you got the blank line For each header line you can parse [fieldName: fieldValue] The end of the headers is signified by CR LF CR LF.

Which Java libraries do HTTP Accept Header Parsing?

You should read this article : http://www.xml.com/pub/a/2005/06/08/restful.html

The article uses Python but it’s not a problem : at the end, the following link is shared : http://code.google.com/p/mimeparse

As you can see, «mimeparse» is :

Basic functions for handling mime-types in Erlang, JavaScript, Perl, PHP, Python, Ruby, Java

According to the home page :

List mimeTypesSupported = Arrays.asList(StringUtils.split( "application/xbel+xml,text/xml", ',')); String bestMatch = MIMEParse.bestMatch(mimeTypesSupported, "text/*;q=0.5,*/*;q=0.1"); 

Have a look at the HttpClient Util.parseHeader method.

Edit: (trying to make this answer worth being accepted post-factum)

The spring framework provides this functionality within its MediaType component.

If you are already using Spring MVC you can simply request for a @RequestHeader -annotated parameter of type HttpHeaders and access the list of accepted media types by simply calling HttpHeaders.getAccept().

HTTP headers | Accept-Language, This HTTP Accept-Language header tells the server about all the languages that the client can understand.

Send HTTP GET Request using Java 11 HttpClient and parse JSON

Best way to parse HTTP headers from HTTP request String using no 3rd party libs (Core Java)

Start by reading and understanding the HTTP specification.

The request line and headers are separated by CR LF sequences (bytes with decimal value 13 and 10), so you can read the stream and separate out each line. I believe that the headers must be encoded in US-ASCII, so you can simply convert bytes to characters and append to a StringBuilder (but check the spec: it may allow ISO-8859-1 or another encoding).

The end of the headers is signified by CR LF CR LF.

I wrote a library, RawHTTP, whose only purpose is to parse HTTP messages (requests and responses).

If you don’t want to use a library, you could copy the source into your own code base, starting form this: https://github.com/renatoathaydes/rawhttp/blob/a6588b116a4008e5b5840d4eb66374c0357b726d/rawhttp-core/src/main/java/com/athaydes/rawhttp/core/RawHttp.java#L52

This will split the lines of the HTTP message all the way to the end of the metadata sections (start-line + headers).

With the list of metadata lines at hand, you can then call the parseHeaders method, which will create the headers for you. You can easily adapt that to just return a Map> to avoid having to also import the header classes.

That said. RawHTTP has no dependencies, so I would just use it instead 🙂 but up to you.

Your concatenated one-line string is not a HTTP header.

A proper HTTP request message should be look like this (not always)

GET / HTTP/1.1 CRLF Host: localhost:9000 CRLF User-Agent: curl/7.19.7 blar blar CRLF Accept: */* CRLF Content-Length: ?? CRLF . . CRLF CRLF octets 

See here http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html

If you want implement a HTTP server without any help of Sevlets, JavaEE Containers, you should use Sockets.

  1. Read the first line [Request-Line = Method SP Request-URI SP HTTP-Version CRLF]
  2. Read the request header line by line till you got the blank line
  3. For each header line you can parse [fieldName: fieldValue]
  4. Read the entity body.

This is NOT the only case for HTTP message contracts.

Should HTTP Client parse HTTP Headers in response with the error, After that the response has the error 404 Not Found and HTTP header is filled with Set-Cookie HTTP Header. The client use Apache Java HTTPClient

Using Volley’s library to Parse Headers from HTTP Response (Android)

Searching on google, I only see ways to access the header information (like —include) is from within the Response parseNetworkResponse(NetworkResponse response) function from Volley. The following is from user thedude’s answer at Android Volley read and store HTTP Header.

@Override protected Response parseNetworkResponse(NetworkResponse response) < try < String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); JSONObject jsonResponse = new JSONObject(jsonString); // set token after receiving from login response TokenHandler.setToken(response.headers.get("x-auth")); return Response.success(jsonResponse, HttpHeaderParser.parseCacheHeaders(response)); >catch (UnsupportedEncodingException | JSONException e) < return Response.error(new ParseError(e)); >> 

Because this is a static context, the only way I’ve found to store the information is as a public variable of another class. The answer fromm thedude uses a TokenHandler.java class:

public final class TokenHandler < private TokenHandler() <>private static String token = ""; public static void setToken(String newToken) < if (newToken != null) token = newToken; >public static String getToken() < return token; >> 

Источник

Java parse http headers

This file is included in the DevDaily.com «Java Source Code Warehouse» project. The intent of this project is to help you «Learn Java by Example» TM .

The source code

/* * $Header: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpParser.java,v 1.7.2.1 2004/02/22 18:21:13 olegk Exp $ * $Revision: 1.7.2.1 $ * $Date: 2004/02/22 18:21:13 $ * * ==================================================================== * * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A utility class for parsing http header values. * * @author Michael Becke * @author Oleg Kalnichevski * * @since 2.0beta1 */ public class HttpParser < /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpParser.class); /** * Constructor for HttpParser. */ private HttpParser() < >/** * Return byte array from an (unchunked) input stream. * Stop reading when "\n" terminator encountered * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * If no input data available, null is returned * * @param inputStream the stream to read from * * @throws IOException if an I/O problem occurs * @return a byte array from the stream */ public static byte[] readRawLine(InputStream inputStream) throws IOException < LOG.trace("enter HttpParser.readRawLine()"); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) >= 0) < buf.write(ch); if (ch == '\n') < break; >> if (buf.size() == 0) < return null; >return buf.toByteArray(); > /** * Read up to "\n" from an (unchunked) input stream. * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * If no input data available, null is returned * * @param inputStream the stream to read from * * @throws IOException if an I/O problem occurs * @return a line from the stream */ public static String readLine(InputStream inputStream) throws IOException < LOG.trace("enter HttpParser.readLine()"); byte[] rawdata = readRawLine(inputStream); if (rawdata == null) < return null; >int len = rawdata.length; int offset = 0; if (len > 0) < if (rawdata[len - 1] == '\n') < offset++; if (len >1) < if (rawdata[len - 2] == '\r') < offset++; >> > > return HttpConstants.getString(rawdata, 0, len - offset); > /** * Parses headers from the given stream. Headers with the same name are not * combined. * * @param is the stream to read headers from * * @return an array of headers in the order in which they were parsed * * @throws IOException if an IO error occurs while reading from the stream * @throws HttpException if there is an error parsing a header value */ public static Header[] parseHeaders(InputStream is) throws IOException, HttpException < LOG.trace("enter HeaderParser.parseHeaders(HttpConnection, HeaderGroup)"); ArrayList headers = new ArrayList(); String name = null; StringBuffer value = null; for (; ;) < String line = HttpParser.readLine(is); if ((line == null) || (line.length() < 1)) < break; >// Parse the header name and value // Check for folded headers first // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 // discussion on folded headers if ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) < // we have continuation folded header // so append value if (value != null) < value.append(' '); value.append(line.trim()); >> else < // make sure we save the previous name,value pair if present if (name != null) < headers.add(new Header(name, value.toString())); >// Otherwise we should have normal HTTP header line // Parse the header name and value int colon = line.indexOf(":"); if (colon < 0) < throw new HttpException("Unable to parse header: " + line); >name = line.substring(0, colon).trim(); value = new StringBuffer(line.substring(colon + 1).trim()); > > // make sure we save the last name,value pair if present if (name != null) < headers.add(new Header(name, value.toString())); >return (Header[]) headers.toArray(new Header[headers.size()]); > >

Источник

Оцените статью