Search in sources :

Example 26 with ParseException

use of org.apache.http.ParseException in project XobotOS by xamarin.

the class LaxContentLengthStrategy method determineLength.

public long determineLength(final HttpMessage message) throws HttpException {
    if (message == null) {
        throw new IllegalArgumentException("HTTP message may not be null");
    }
    HttpParams params = message.getParams();
    boolean strict = params.isParameterTrue(CoreProtocolPNames.STRICT_TRANSFER_ENCODING);
    Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
    Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
    // RFC2616, 4.4 item number 3
    if (transferEncodingHeader != null) {
        HeaderElement[] encodings = null;
        try {
            encodings = transferEncodingHeader.getElements();
        } catch (ParseException px) {
            throw new ProtocolException("Invalid Transfer-Encoding header value: " + transferEncodingHeader, px);
        }
        if (strict) {
            // Currently only chunk and identity are supported
            for (int i = 0; i < encodings.length; i++) {
                String encoding = encodings[i].getName();
                if (encoding != null && encoding.length() > 0 && !encoding.equalsIgnoreCase(HTTP.CHUNK_CODING) && !encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) {
                    throw new ProtocolException("Unsupported transfer encoding: " + encoding);
                }
            }
        }
        // The chunked encoding must be the last one applied RFC2616, 14.41
        int len = encodings.length;
        if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
            return IDENTITY;
        } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase(encodings[len - 1].getName()))) {
            return CHUNKED;
        } else {
            if (strict) {
                throw new ProtocolException("Chunk-encoding must be the last one applied");
            }
            return IDENTITY;
        }
    } else if (contentLengthHeader != null) {
        long contentlen = -1;
        Header[] headers = message.getHeaders(HTTP.CONTENT_LEN);
        if (strict && headers.length > 1) {
            throw new ProtocolException("Multiple content length headers");
        }
        for (int i = headers.length - 1; i >= 0; i--) {
            Header header = headers[i];
            try {
                contentlen = Long.parseLong(header.getValue());
                break;
            } catch (NumberFormatException e) {
                if (strict) {
                    throw new ProtocolException("Invalid content length: " + header.getValue());
                }
            }
        // See if we can have better luck with another header, if present
        }
        if (contentlen >= 0) {
            return contentlen;
        } else {
            return IDENTITY;
        }
    } else {
        return IDENTITY;
    }
}
Also used : ProtocolException(org.apache.http.ProtocolException) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HeaderElement(org.apache.http.HeaderElement) ParseException(org.apache.http.ParseException)

Example 27 with ParseException

use of org.apache.http.ParseException in project XobotOS by xamarin.

the class AbstractMessageParser method parseHeaders.

/**
     * 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
     * @return array of HTTP headers
     * 
     * @throws HttpException
     * @throws IOException
     */
public static Header[] parseHeaders(final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, LineParser parser) throws HttpException, IOException {
    if (inbuffer == null) {
        throw new IllegalArgumentException("Session input buffer may not be null");
    }
    if (parser == null)
        parser = BasicLineParser.DEFAULT;
    ArrayList headerLines = new ArrayList();
    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;
        }
        // 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;
}
Also used : ProtocolException(org.apache.http.ProtocolException) Header(org.apache.http.Header) ArrayList(java.util.ArrayList) CharArrayBuffer(org.apache.http.util.CharArrayBuffer) IOException(java.io.IOException) ParseException(org.apache.http.ParseException)

Example 28 with ParseException

use of org.apache.http.ParseException in project XobotOS by xamarin.

the class DefaultConnectionReuseStrategy method keepAlive.

// see interface ConnectionReuseStrategy
public boolean keepAlive(final HttpResponse response, final HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null.");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null.");
    }
    HttpConnection conn = (HttpConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
    if (conn != null && !conn.isOpen())
        return false;
    // do NOT check for stale connection, that is an expensive operation
    // Check for a self-terminating entity. If the end of the entity will
    // be indicated by closing the connection, there is no keep-alive.
    HttpEntity entity = response.getEntity();
    ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
    if (entity != null) {
        if (entity.getContentLength() < 0) {
            if (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0)) {
                // encoded, the connection cannot be reused
                return false;
            }
        }
    }
    // Check for the "Connection" header. If that is absent, check for
    // the "Proxy-Connection" header. The latter is an unspecified and
    // broken but unfortunately common extension of HTTP.
    HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
    if (!hit.hasNext())
        hit = response.headerIterator("Proxy-Connection");
    if (hit.hasNext()) {
        try {
            TokenIterator ti = createTokenIterator(hit);
            boolean keepalive = false;
            while (ti.hasNext()) {
                final String token = ti.nextToken();
                if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
                    return false;
                } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
                    // continue the loop, there may be a "close" afterwards
                    keepalive = true;
                }
            }
            if (keepalive)
                return true;
        // neither "close" nor "keep-alive", use default policy
        } catch (ParseException px) {
            // we don't have logging in HttpCore, so the exception is lost
            return false;
        }
    }
    // default since HTTP/1.1 is persistent, before it was non-persistent
    return !ver.lessEquals(HttpVersion.HTTP_1_0);
}
Also used : HttpEntity(org.apache.http.HttpEntity) TokenIterator(org.apache.http.TokenIterator) BasicTokenIterator(org.apache.http.message.BasicTokenIterator) HttpConnection(org.apache.http.HttpConnection) HeaderIterator(org.apache.http.HeaderIterator) ParseException(org.apache.http.ParseException) ProtocolVersion(org.apache.http.ProtocolVersion)

Example 29 with ParseException

use of org.apache.http.ParseException in project XobotOS by xamarin.

the class AbstractMessageParser method parse.

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;
}
Also used : ProtocolException(org.apache.http.ProtocolException) Header(org.apache.http.Header) ParseException(org.apache.http.ParseException) HttpMessage(org.apache.http.HttpMessage)

Example 30 with ParseException

use of org.apache.http.ParseException in project XobotOS by xamarin.

the class BasicLineParser method parseRequestLine.

/**
     * Parses a request line.
     *
     * @param buffer    a buffer holding the line to parse
     *
     * @return  the parsed request line
     *
     * @throws ParseException        in case of a parse error
     */
public RequestLine parseRequestLine(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException {
    if (buffer == null) {
        throw new IllegalArgumentException("Char array buffer may not be null");
    }
    if (cursor == null) {
        throw new IllegalArgumentException("Parser cursor may not be null");
    }
    int indexFrom = cursor.getPos();
    int indexTo = cursor.getUpperBound();
    try {
        skipWhitespace(buffer, cursor);
        int i = cursor.getPos();
        int blank = buffer.indexOf(' ', i, indexTo);
        if (blank < 0) {
            throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
        }
        String method = buffer.substringTrimmed(i, blank);
        cursor.updatePos(blank);
        skipWhitespace(buffer, cursor);
        i = cursor.getPos();
        blank = buffer.indexOf(' ', i, indexTo);
        if (blank < 0) {
            throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
        }
        String uri = buffer.substringTrimmed(i, blank);
        cursor.updatePos(blank);
        ProtocolVersion ver = parseProtocolVersion(buffer, cursor);
        skipWhitespace(buffer, cursor);
        if (!cursor.atEnd()) {
            throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
        }
        return createRequestLine(method, uri, ver);
    } catch (IndexOutOfBoundsException e) {
        throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
    }
}
Also used : ParseException(org.apache.http.ParseException) ProtocolVersion(org.apache.http.ProtocolVersion)

Aggregations

ParseException (org.apache.http.ParseException)38 Header (org.apache.http.Header)14 ProtocolVersion (org.apache.http.ProtocolVersion)12 IOException (java.io.IOException)10 ProtocolException (org.apache.http.ProtocolException)9 HttpException (org.apache.http.HttpException)6 HttpParams (org.apache.http.params.HttpParams)6 Test (org.junit.Test)5 HttpEntity (org.apache.http.HttpEntity)4 Socket (java.net.Socket)3 UnknownHostException (java.net.UnknownHostException)3 ArrayList (java.util.ArrayList)3 LinkedList (java.util.LinkedList)3 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)3 SSLSocket (javax.net.ssl.SSLSocket)3 HeaderElement (org.apache.http.HeaderElement)3 HeaderIterator (org.apache.http.HeaderIterator)3 HttpConnection (org.apache.http.HttpConnection)3 HttpMessage (org.apache.http.HttpMessage)3 HttpResponse (org.apache.http.HttpResponse)3