org.apache.http.HttpMessage - java examples

Here are the examples of the java api org.apache.http.HttpMessage taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

59 Examples 7

19 View Complete Implementation : AbstractMessageParser.java
Copyright GNU General Public License v3.0
Author : onedanshow
public HttpMessage parse() throws IOException, HttpException {
    int st = this.state;
    switch(st) {
        case HEAD_LINE:
            try {
                this.message = parseHead(this.sessionBuffer);
            } catch (ParseException px) {
                throw new ProtocolException(px.getMessage(), px);
            }
            this.state = HEADERS;
        // $FALL-THROUGH$
        case HEADERS:
            Header[] headers = AbstractMessageParser.parseHeaders(this.sessionBuffer, this.maxHeaderCount, this.maxLineLen, this.lineParser, this.headerLines);
            this.message.setHeaders(headers);
            HttpMessage result = this.message;
            this.message = null;
            this.headerLines.clear();
            this.state = HEAD_LINE;
            return result;
        default:
            throw new IllegalStateException("Inconsistent parser state");
    }
}

19 View Complete Implementation : HttpResponseWriter.java
Copyright GNU General Public License v3.0
Author : onedanshow
protected void writeHeadLine(final HttpMessage message) throws IOException {
    lineFormatter.formatStatusLine(this.lineBuf, ((HttpResponse) message).getStatusLine());
    this.sessionBuffer.writeLine(this.lineBuf);
}

19 View Complete Implementation : HTTPEngine4Impl.java
Copyright GNU Lesser General Public License v2.1
Author : lucee
private static void setUserAgent(HttpMessage hm, String useragent) {
    if (useragent != null)
        hm.setHeader("User-Agent", useragent);
}

19 View Complete Implementation : EntityDeserializer.java
Copyright GNU General Public License v3.0
Author : onedanshow
/**
 * Creates an {@link HttpEnreplacedy} based on properties of the given message.
 * The content of the enreplacedy is created by wrapping
 * {@link SessionInputBuffer} with a content decoder depending on the
 * transfer mechanism used by the message.
 * <p>
 * The content of the enreplacedy is NOT retrieved by this method.
 *
 * @param inbuffer the session input buffer.
 * @param message the message.
 * @return HTTP enreplacedy.
 * @throws HttpException in case of HTTP protocol violation.
 * @throws IOException in case of an I/O error.
 */
public HttpEnreplacedy deserialize(final SessionInputBuffer inbuffer, final HttpMessage message) throws HttpException, IOException {
    if (inbuffer == null) {
        throw new IllegalArgumentException("Session input buffer may not be null");
    }
    if (message == null) {
        throw new IllegalArgumentException("HTTP message may not be null");
    }
    return doDeserialize(inbuffer, message);
}

19 View Complete Implementation : AbstractMessageParser.java
Copyright MIT License
Author : pivotal-legacy
public HttpMessage parse() throws IOException, HttpException {
    HttpMessage message = null;
    try {
        message = parseHead(this.sessionBuffer);
    } catch (ParseException px) {
        throw new ProtocolException(px.getMessage(), px);
    }
    Header[] headers = AbstractMessageParser.parseHeaders(this.sessionBuffer, this.maxHeaderCount, this.maxLineLen, this.lineParser);
    message.setHeaders(headers);
    return message;
}

19 View Complete Implementation : HTTPEngine4Impl.java
Copyright GNU Lesser General Public License v2.1
Author : lucee
private static void addHeader(HttpMessage hm, lucee.commons.net.http.Header[] headers) {
    if (headers != null) {
        for (int i = 0; i < headers.length; i++) hm.addHeader(toHeader(headers[i]));
    }
}

19 View Complete Implementation : HttpRequestWriter.java
Copyright GNU General Public License v3.0
Author : onedanshow
protected void writeHeadLine(final HttpMessage message) throws IOException {
    lineFormatter.formatRequestLine(this.lineBuf, ((HttpRequest) message).getRequestLine());
    this.sessionBuffer.writeLine(this.lineBuf);
}

19 View Complete Implementation : InMemoryCacheEntry.java
Copyright Mozilla Public License 2.0
Author : GistLabs
protected void transferFirstHeader(final String headerName, final HttpMessage origin, final HttpMessage dest) {
    transferFirstHeader(headerName, headerName, origin, dest);
}

19 View Complete Implementation : EntityDeserializer.java
Copyright MIT License
Author : pivotal-legacy
public HttpEnreplacedy deserialize(final SessionInputBuffer inbuffer, final HttpMessage message) throws HttpException, IOException {
    if (inbuffer == null) {
        throw new IllegalArgumentException("Session input buffer may not be null");
    }
    if (message == null) {
        throw new IllegalArgumentException("HTTP message may not be null");
    }
    return doDeserialize(inbuffer, message);
}

19 View Complete Implementation : InMemoryCacheEntry.java
Copyright Mozilla Public License 2.0
Author : GistLabs
protected boolean has(final String headerName, final HttpMessage message) {
    return message.getHeaders(headerName).length > 0;
}

19 View Complete Implementation : HTTPEngine4Impl.java
Copyright GNU Lesser General Public License v2.1
Author : lucee
private static void setHeader(HttpMessage hm, lucee.commons.net.http.Header[] headers) {
    addHeader(hm, headers);
}

19 View Complete Implementation : Client.java
Copyright MIT License
Author : sendgrid
private void writeContentTypeIfNeeded(Request request, HttpMessage httpMessage) {
    if (!"".equals(request.getBody())) {
        httpMessage.setHeader("Content-Type", "application/json");
    }
}

19 View Complete Implementation : OtrDataHandler.java
Copyright Apache License 2.0
Author : guardianproject
private void sendResponse(Address us, int code, String statusString, String uid, byte[] body) {
    MemorySessionOutputBuffer outBuf = new MemorySessionOutputBuffer();
    HttpMessageWriter writer = new HttpResponseWriter(outBuf, lineFormatter, params);
    HttpMessage response = new BasicHttpResponse(new BasicStatusLine(PROTOCOL_VERSION, code, statusString));
    response.addHeader("Request-Id", uid);
    try {
        writer.write(response);
        outBuf.write(body);
        outBuf.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    }
    byte[] data = outBuf.getOutput();
    Message message = new Message("");
    message.setFrom(us);
    debug("send response " + statusString + " for " + uid);
    mChatSession.sendDataAsync(message, true, data);
}

19 View Complete Implementation : HTTPEngine4Impl.java
Copyright GNU Lesser General Public License v2.1
Author : lucee
private static void setContentType(HttpMessage hm, String charset) {
    if (charset != null)
        hm.setHeader("Content-type", "text/html; charset=" + charset);
}

18 View Complete Implementation : HttpClientFactory.java
Copyright GNU General Public License v3.0
Author : atomist-attic
public static void authorizationHeader(HttpMessage msg, String username, String preplacedword) {
    if (username != null && preplacedword != null) {
        msg.addHeader("Authorization", encodeBaseAuthHeader(username, preplacedword));
    }
}

18 View Complete Implementation : HttpClientFactory.java
Copyright GNU General Public License v3.0
Author : atomist-attic
public static void header(HttpMessage msg, String key, String value) {
    if (value != null) {
        msg.addHeader(key, value);
    }
}

18 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
@Override
protected String getTransactionName(HttpMessage requestContext) {
    return null;
}

18 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
@Override
protected void specialHandling(HttpMessage request) {
}

18 View Complete Implementation : WeaveTransport.java
Copyright Apache License 2.0
Author : emergentdotorg
private void setMethodHeaders(HttpMessage method) {
    method.addHeader("Pragma", "no-cache");
    method.addHeader("Cache-Control", "no-cache");
}

18 View Complete Implementation : BatchRefineTransformer.java
Copyright Apache License 2.0
Author : fusepoolP3
protected void logMessage(HttpMessage message) {
    if (fLogger.isDebugEnabled()) {
        fLogger.debug(message.toString());
    }
}

18 View Complete Implementation : InMemoryCacheEntry.java
Copyright Mozilla Public License 2.0
Author : GistLabs
protected void transferFirstHeader(final String headerName, final String destName, final HttpMessage origin, final HttpMessage dest) {
    Header header = origin.getFirstHeader(headerName);
    if (header != null)
        dest.setHeader(destName, header.getValue());
}

18 View Complete Implementation : InMemoryCacheEntry.java
Copyright Mozilla Public License 2.0
Author : GistLabs
protected String get(final String headerName, final HttpMessage message) {
    Header header = message.getFirstHeader(headerName);
    if (header != null)
        return header.getValue();
    else
        return "";
}

18 View Complete Implementation : OtrDataHandler.java
Copyright Apache License 2.0
Author : guardianproject
private void sendRequest(Request request) {
    MemorySessionOutputBuffer outBuf = new MemorySessionOutputBuffer();
    HttpMessageWriter writer = new HttpRequestWriter(outBuf, lineFormatter, params);
    HttpMessage req = new BasicHttpRequest(request.method, request.url, PROTOCOL_VERSION);
    String uid = UUID.randomUUID().toString();
    req.addHeader("Request-Id", uid);
    if (request.headers != null) {
        for (Entry<String, String> entry : request.headers.entrySet()) {
            req.addHeader(entry.getKey(), entry.getValue());
        }
    }
    try {
        writer.write(req);
        outBuf.write(request.body);
        outBuf.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    }
    byte[] data = outBuf.getOutput();
    Message message = new Message("");
    message.setFrom(request.us);
    if (req.containsHeader("Range"))
        debug("send request " + request.method + " " + request.url + " " + req.getFirstHeader("Range"));
    else
        debug("send request " + request.method + " " + request.url);
    requestCache.put(uid, request);
    mChatSession.sendDataAsync(message, false, data);
}

18 View Complete Implementation : DecodeServlet.java
Copyright Apache License 2.0
Author : joelind
private static boolean isSizeOK(HttpMessage getResponse) {
    Header lengthHeader = getResponse.getLastHeader("Content-Length");
    if (lengthHeader != null) {
        long length = Long.parseLong(lengthHeader.getValue());
        if (length > MAX_IMAGE_SIZE) {
            return false;
        }
    }
    return true;
}

18 View Complete Implementation : EntitySerializer.java
Copyright GNU General Public License v3.0
Author : onedanshow
/**
 * Creates a transfer codec based on properties of the given HTTP message
 * and returns {@link OutputStream} instance that transparently encodes
 * output data as it is being written out to the output stream.
 * <p>
 * This method is called by the public
 * {@link #serialize(SessionOutputBuffer, HttpMessage, HttpEnreplacedy)}.
 *
 * @param outbuffer the session output buffer.
 * @param message the HTTP message.
 * @return output stream.
 * @throws HttpException in case of HTTP protocol violation.
 * @throws IOException in case of an I/O error.
 */
protected OutputStream doSerialize(final SessionOutputBuffer outbuffer, final HttpMessage message) throws HttpException, IOException {
    long len = this.lenStrategy.determineLength(message);
    if (len == ContentLengthStrategy.CHUNKED) {
        return new ChunkedOutputStream(outbuffer);
    } else if (len == ContentLengthStrategy.IDENreplacedY) {
        return new IdenreplacedyOutputStream(outbuffer);
    } else {
        return new ContentLengthOutputStream(outbuffer, len);
    }
}

18 View Complete Implementation : AbstractMessageWriter.java
Copyright GNU General Public License v3.0
Author : onedanshow
public void write(final HttpMessage message) throws IOException, HttpException {
    if (message == null) {
        throw new IllegalArgumentException("HTTP message may not be null");
    }
    writeHeadLine(message);
    for (Iterator it = message.headerIterator(); it.hasNext(); ) {
        Header header = (Header) it.next();
        this.sessionBuffer.writeLine(lineFormatter.formatHeader(this.lineBuf, header));
    }
    this.lineBuf.clear();
    this.sessionBuffer.writeLine(this.lineBuf);
}

18 View Complete Implementation : EntitySerializer.java
Copyright MIT License
Author : pivotal-legacy
protected OutputStream doSerialize(final SessionOutputBuffer outbuffer, final HttpMessage message) throws HttpException, IOException {
    long len = this.lenStrategy.determineLength(message);
    if (len == ContentLengthStrategy.CHUNKED) {
        return new ChunkedOutputStream(outbuffer);
    } else if (len == ContentLengthStrategy.IDENreplacedY) {
        return new IdenreplacedyOutputStream(outbuffer);
    } else {
        return new ContentLengthOutputStream(outbuffer, len);
    }
}

18 View Complete Implementation : HttpRequestWriter.java
Copyright MIT License
Author : pivotal-legacy
protected void writeHeadLine(final HttpMessage message) throws IOException {
    final CharArrayBuffer buffer = lineFormatter.formatRequestLine(this.lineBuf, ((HttpRequest) message).getRequestLine());
    this.sessionBuffer.writeLine(buffer);
}

18 View Complete Implementation : HttpResponseWriter.java
Copyright MIT License
Author : pivotal-legacy
protected void writeHeadLine(final HttpMessage message) throws IOException {
    final CharArrayBuffer buffer = lineFormatter.formatStatusLine(this.lineBuf, ((HttpResponse) message).getStatusLine());
    this.sessionBuffer.writeLine(buffer);
}

18 View Complete Implementation : HttpClientFactory.java
Copyright GNU General Public License v3.0
Author : atomist-attic
public static void authorizationHeader(HttpMessage msg, String token) {
    if (token != null) {
        msg.addHeader("Authorization", "Bearer " + token);
    }
}

18 View Complete Implementation : DefaultHttpClientHelper.java
Copyright GNU Affero General Public License v3.0
Author : temenostech
/**
 * Builds and returns the {@link HttpMessage http message} with the request
 * headers.
 *
 * @param request
 * @param message
 */
public static void buildRequestHeaders(HttpRequest request, HttpMessage message) {
    HttpHeader header = request.headers();
    for (String name : header.names()) {
        message.addHeader(name, header.get(name));
    }
}

17 View Complete Implementation : HttpClientRequestor.java
Copyright MIT License
Author : dadiyang
private void addCookies(HttpRequest request, HttpMessage msg) {
    Map<String, String> cookies = request.getCookies();
    if (cookies == null || cookies.isEmpty()) {
        return;
    }
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : cookies.entrySet()) {
        sb.append(entry.getKey()).append("=").append(entry.getValue()).append(";");
    }
    msg.addHeader("Cookie", sb.substring(0, sb.length()));
}

17 View Complete Implementation : HttpClientRequestor.java
Copyright MIT License
Author : dadiyang
private void addHeaders(HttpRequest request, HttpMessage msg) {
    Map<String, String> headers = request.getHeaders();
    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            msg.addHeader(entry.getKey(), entry.getValue());
        }
    }
}

17 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
private Transaction logTransaction(HttpMessage message, URI uri, String method) {
    Transaction transaction;
    transaction = this.newTransaction(this.getTransactionType(), uri.getScheme() + "://" + uri.getAuthority() + getConcreteUri(uri.getPath()));
    sendClientAddr(message, getClientAddrDataKey(), getClientAddrData());
    sendClientDomain(message, getClientDomainDataKey(), getClientDomainData());
    Cat.logEvent("Http.Method", method);
    logRemoteTrace(message);
    return transaction;
}

17 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
@Override
protected void sendClientAddr(HttpMessage request, String key, String value) {
    request.setHeader(key, value);
}

17 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
@Override
protected void sendClientDomain(HttpMessage request, String key, String value) {
    request.setHeader(key, value);
}

17 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
@Override
public void logTrace(HttpMessage handler, Entry<String, String> entry) {
    handler.setHeader(entry.getKey(), entry.getValue());
}

17 View Complete Implementation : HttpActivityExecutor.java
Copyright Apache License 2.0
Author : flowable
protected void setHeaders(final HttpMessage base, final String headers) throws IOException {
    try (BufferedReader reader = new BufferedReader(new StringReader(headers))) {
        String line = reader.readLine();
        while (line != null) {
            int colonIndex = line.indexOf(':');
            if (colonIndex > 0) {
                String headerName = line.substring(0, colonIndex);
                if (line.length() > colonIndex + 2) {
                    base.addHeader(headerName, line.substring(colonIndex + 1));
                } else {
                    base.addHeader(headerName, null);
                }
                line = reader.readLine();
            } else {
                throw new FlowableException(HTTP_TASK_REQUEST_HEADERS_INVALID);
            }
        }
    }
}

17 View Complete Implementation : InMemoryCacheEntry.java
Copyright Mozilla Public License 2.0
Author : GistLabs
protected boolean has(final String headerName, final String headerValueOrElement, final HttpMessage message) {
    Header[] headers = message.getHeaders(headerName);
    for (Header header : headers) {
        if (header.getValue().equals(headerValueOrElement))
            return true;
        HeaderElement[] elements = header.getElements();
        for (HeaderElement element : elements) if (element.getName().equals(headerValueOrElement))
            return true;
    }
    return false;
}

17 View Complete Implementation : HeaderUtil.java
Copyright GNU General Public License v2.0
Author : kingthy
public static void add(HttpMessage httpMessage, Headers headers) {
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        for (String value : entry.getValue()) {
            httpMessage.addHeader(entry.getKey(), value);
        }
    }
}

17 View Complete Implementation : AbstractMessageParser.java
Copyright GNU General Public License v3.0
Author : onedanshow
/**
 * Abstract base clreplaced for HTTP message parsers that obtain input from
 * an instance of {@link SessionInputBuffer}.
 * <p>
 * The following parameters can be used to customize the behavior of this
 * clreplaced:
 * <ul>
 *  <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
 *  <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
 * </ul>
 *
 * @since 4.0
 */
public abstract clreplaced AbstractMessageParser implements HttpMessageParser {

    private static final int HEAD_LINE = 0;

    private static final int HEADERS = 1;

    private final SessionInputBuffer sessionBuffer;

    private final int maxHeaderCount;

    private final int maxLineLen;

    private final List headerLines;

    protected final LineParser lineParser;

    private int state;

    private HttpMessage message;

    /**
     * Creates an instance of this clreplaced.
     *
     * @param buffer the session input buffer.
     * @param parser the line parser.
     * @param params HTTP parameters.
     */
    public AbstractMessageParser(final SessionInputBuffer buffer, final LineParser parser, final HttpParams params) {
        super();
        if (buffer == null) {
            throw new IllegalArgumentException("Session input buffer may not be null");
        }
        if (params == null) {
            throw new IllegalArgumentException("HTTP parameters may not be null");
        }
        this.sessionBuffer = buffer;
        this.maxHeaderCount = params.getIntParameter(CoreConnectionPNames.MAX_HEADER_COUNT, -1);
        this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1);
        this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT;
        this.headerLines = new ArrayList();
        this.state = HEAD_LINE;
    }

    /**
     * Parses HTTP headers from the data receiver stream according to the generic
     * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3.
     *
     * @param inbuffer Session input buffer
     * @param maxHeaderCount maximum number of headers allowed. If the number
     *  of headers received from the data stream exceeds maxCount value, an
     *  IOException will be thrown. Setting this parameter to a negative value
     *  or zero will disable the check.
     * @param maxLineLen maximum number of characters for a header line,
     *  including the continuation lines. Setting this parameter to a negative
     *  value or zero will disable the check.
     * @return array of HTTP headers
     * @param parser line parser to use. Can be <code>null</code>, in which case
     *  the default implementation of this interface will be used.
     *
     * @throws IOException in case of an I/O error
     * @throws HttpException in case of HTTP protocol violation
     */
    public static Header[] parseHeaders(final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, LineParser parser) throws HttpException, IOException {
        if (parser == null) {
            parser = BasicLineParser.DEFAULT;
        }
        List headerLines = new ArrayList();
        return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, parser, headerLines);
    }

    /**
     * Parses HTTP headers from the data receiver stream according to the generic
     * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3.
     *
     * @param inbuffer Session input buffer
     * @param maxHeaderCount maximum number of headers allowed. If the number
     *  of headers received from the data stream exceeds maxCount value, an
     *  IOException will be thrown. Setting this parameter to a negative value
     *  or zero will disable the check.
     * @param maxLineLen maximum number of characters for a header line,
     *  including the continuation lines. Setting this parameter to a negative
     *  value or zero will disable the check.
     * @param parser line parser to use.
     * @param headerLines List of header lines. This list will be used to store
     *   intermediate results. This makes it possible to resume parsing of
     *   headers in case of a {@link java.io.InterruptedIOException}.
     *
     * @return array of HTTP headers
     *
     * @throws IOException in case of an I/O error
     * @throws HttpException in case of HTTP protocol violation
     *
     * @since 4.1
     */
    public static Header[] parseHeaders(final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, final LineParser parser, final List headerLines) throws HttpException, IOException {
        if (inbuffer == null) {
            throw new IllegalArgumentException("Session input buffer may not be null");
        }
        if (parser == null) {
            throw new IllegalArgumentException("Line parser may not be null");
        }
        if (headerLines == null) {
            throw new IllegalArgumentException("Header line list may not be null");
        }
        CharArrayBuffer current = null;
        CharArrayBuffer previous = null;
        for (; ; ) {
            if (current == null) {
                current = new CharArrayBuffer(64);
            } else {
                current.clear();
            }
            int l = inbuffer.readLine(current);
            if (l == -1 || current.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 ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) {
                // we have continuation folded header
                // so append value
                int i = 0;
                while (i < current.length()) {
                    char ch = current.charAt(i);
                    if (ch != ' ' && ch != '\t') {
                        break;
                    }
                    i++;
                }
                if (maxLineLen > 0 && previous.length() + 1 + current.length() - i > maxLineLen) {
                    throw new IOException("Maximum line length limit exceeded");
                }
                previous.append(' ');
                previous.append(current, i, current.length() - i);
            } else {
                headerLines.add(current);
                previous = current;
                current = null;
            }
            if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) {
                throw new IOException("Maximum header count exceeded");
            }
        }
        Header[] headers = new Header[headerLines.size()];
        for (int i = 0; i < headerLines.size(); i++) {
            CharArrayBuffer buffer = (CharArrayBuffer) headerLines.get(i);
            try {
                headers[i] = parser.parseHeader(buffer);
            } catch (ParseException ex) {
                throw new ProtocolException(ex.getMessage());
            }
        }
        return headers;
    }

    /**
     * Subclreplacedes must override this method to generate an instance of
     * {@link HttpMessage} based on the initial input from the session buffer.
     * <p>
     * Usually this method is expected to read just the very first line or
     * the very first valid from the data stream and based on the input generate
     * an appropriate instance of {@link HttpMessage}.
     *
     * @param sessionBuffer the session input buffer.
     * @return HTTP message based on the input from the session buffer.
     * @throws IOException in case of an I/O error.
     * @throws HttpException in case of HTTP protocol violation.
     * @throws ParseException in case of a parse error.
     */
    protected abstract HttpMessage parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException;

    public HttpMessage parse() throws IOException, HttpException {
        int st = this.state;
        switch(st) {
            case HEAD_LINE:
                try {
                    this.message = parseHead(this.sessionBuffer);
                } catch (ParseException px) {
                    throw new ProtocolException(px.getMessage(), px);
                }
                this.state = HEADERS;
            // $FALL-THROUGH$
            case HEADERS:
                Header[] headers = AbstractMessageParser.parseHeaders(this.sessionBuffer, this.maxHeaderCount, this.maxLineLen, this.lineParser, this.headerLines);
                this.message.setHeaders(headers);
                HttpMessage result = this.message;
                this.message = null;
                this.headerLines.clear();
                this.state = HEAD_LINE;
                return result;
            default:
                throw new IllegalStateException("Inconsistent parser state");
        }
    }
}

17 View Complete Implementation : HttpAction.java
Copyright Apache License 2.0
Author : personium
/**
 * Set common headers.
 * @param req HttpMessage object
 * @param event PersoniumEvent object
 */
protected void setCommonHeaders(HttpMessage req, PersoniumEvent event) {
    // set common headers
    // X-Personium-RequestKey, X-Personium-EventId, X-Personium-RuleChain, X-Personium-Via
    event.getRequestKey().ifPresent(requestKey -> req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY, requestKey));
    req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_EVENTID, eventId);
    req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_RULECHAIN, chain);
    getVia(event).ifPresent(via -> req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_VIA, via));
}

17 View Complete Implementation : DefaultCosHttpClient.java
Copyright MIT License
Author : tencentyun
/**
 * 设置Http头部,同时添加上公共的类型,长连接,COS SDK标识
 *
 * @param message
 *            HTTP消息
 * @param headers
 *            用户额外添加的HTTP头部
 */
private void setHeaders(HttpMessage message, Map<String, String> headers) {
    message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL);
    message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE);
    message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());
    if (headers != null) {
        for (String headerKey : headers.keySet()) {
            message.setHeader(headerKey, headers.get(headerKey));
        }
    }
}

17 View Complete Implementation : DefaultCosHttpClient.java
Copyright MIT License
Author : tencentyun
/**
 * 设置Http头部,同时添加上公共的类型,长连接,COS SDK标识
 *
 * @param message HTTP消息
 * @param headers 用户额外添加的HTTP头部
 */
private void setHeaders(HttpMessage message, Map<String, String> headers) {
    message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL);
    message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE);
    message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());
    if (headers != null) {
        for (String headerKey : headers.keySet()) {
            message.setHeader(headerKey, headers.get(headerKey));
        }
    }
}

16 View Complete Implementation : HttpClientPluginTemplate.java
Copyright Apache License 2.0
Author : dianping
@Override
public boolean enableTrace(HttpMessage handler) {
    handler.setHeader(CatPluginConstants.D_CALL_TRACE_MODE, "trace");
    return true;
}

16 View Complete Implementation : AbstractResource.java
Copyright Mozilla Public License 2.0
Author : GistLabs
private void write(final HttpMessage message, final PrintWriter writer) {
    Header[] headers = message.getAllHeaders();
    for (Header header : headers) writer.println(header.toString());
}

16 View Complete Implementation : InMemoryCacheEntry.java
Copyright Mozilla Public License 2.0
Author : GistLabs
protected String get(final String headerName, final String elementName, final HttpMessage message) {
    Header header = message.getFirstHeader(headerName);
    if (header == null)
        return "";
    HeaderElement[] elements = header.getElements();
    for (HeaderElement element : elements) if (element.getName().equals(elementName))
        return element.getValue();
    return "";
}

15 View Complete Implementation : CachingHttpClient.java
Copyright Apache License 2.0
Author : apigee
private String generateViaHeader(HttpMessage msg) {
    final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClreplaced().getClreplacedLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    final ProtocolVersion pv = msg.getProtocolVersion();
    if ("http".equalsIgnoreCase(pv.getProtocol())) {
        return String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getMajor(), pv.getMinor(), release);
    } else {
        return String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), pv.getMajor(), pv.getMinor(), release);
    }
}

15 View Complete Implementation : ResponseCachingPolicy.java
Copyright Apache License 2.0
Author : apigee
protected boolean hasCacheControlParameterFrom(HttpMessage msg, String[] params) {
    Header[] cacheControlHeaders = msg.getHeaders(HeaderConstants.CACHE_CONTROL);
    for (Header header : cacheControlHeaders) {
        for (HeaderElement elem : header.getElements()) {
            for (String param : params) {
                if (param.equalsIgnoreCase(elem.getName())) {
                    return true;
                }
            }
        }
    }
    return false;
}

15 View Complete Implementation : HeaderUtil.java
Copyright GNU General Public License v2.0
Author : kingthy
public static Headers get(HttpMessage httpMessage) {
    Headers headers = new Headers();
    for (Header header : httpMessage.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    return headers;
}