Search in sources :

Example 1 with ParseException

use of org.apache.hc.core5.http.ParseException in project chatty by chatty.

the class Request method apache.

private void apache() {
    if (listener == null) {
        return;
    }
    String responseText = null;
    int responseCode = -1;
    int ratelimitRemaining = -1;
    String responseEncoding = null;
    String requestError = null;
    LOGGER.info(String.format("%s*%s: %s", requestMethod, token != null ? " (auth) " : "", url));
    RequestConfig config = RequestConfig.custom().setConnectTimeout(Timeout.ofMilliseconds(CONNECT_TIMEOUT)).setResponseTimeout(30, TimeUnit.SECONDS).build();
    try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
        ClassicHttpRequest request = new HttpUriRequestBase(requestMethod, new URI(url));
        request.addHeader("Client-ID", CLIENT_ID);
        if (token != null) {
            request.addHeader("Authorization", "Bearer " + token);
        }
        if (data != null) {
            StringEntity stringEntity;
            if (contentType.equals("application/json")) {
                stringEntity = new StringEntity(data, ContentType.APPLICATION_JSON, "UTF-8", false);
            } else {
                stringEntity = new StringEntity(data, CHARSET);
            }
            request.setEntity(stringEntity);
            LOGGER.info("Sending data: " + data);
        }
        try (CloseableHttpResponse response = httpclient.execute(request)) {
            responseCode = response.getCode();
            responseEncoding = getStringHeader(response.getFirstHeader("Content-Encoding"), null);
            ratelimitRemaining = getIntHeader(response.getFirstHeader("Ratelimit-Remaining"), -1);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                responseText = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                EntityUtils.consume(responseEntity);
            }
        }
    } catch (IOException | URISyntaxException | ParseException ex) {
        requestError = ex.toString();
    }
    // -----------------------
    // Debug output / Output
    // -----------------------
    LOGGER.info(String.format("GOT (%d/%d, %d%s): %s%s", responseCode, ratelimitRemaining, responseText != null ? responseText.length() : -1, responseEncoding != null ? ", " + responseEncoding : "", url, requestError != null ? " [" + requestError + "]" : ""));
    listener.requestResult(responseText, responseCode, ratelimitRemaining);
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) HttpEntity(org.apache.hc.core5.http.HttpEntity) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ParseException(org.apache.hc.core5.http.ParseException)

Example 2 with ParseException

use of org.apache.hc.core5.http.ParseException in project logbook by zalando.

the class AbstractHttpTest method shouldLogResponseWithBody.

@Test
void shouldLogResponseWithBody() throws IOException, ExecutionException, InterruptedException, ParseException {
    driver.addExpectation(onRequestTo("/").withMethod(POST), giveResponse("Hello, world!", "text/plain"));
    final ClassicHttpResponse response = sendAndReceive("Hello, world!");
    assertThat(response.getCode()).isEqualTo(200);
    assertThat(response.getEntity()).isNotNull();
    assertThat(EntityUtils.toString(response.getEntity())).isEqualTo("Hello, world!");
    final String message = captureResponse();
    assertThat(message).startsWith("Incoming Response:").contains("HTTP/1.1 200 OK", "Content-Type: text/plain", "Hello, world!");
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 3 with ParseException

use of org.apache.hc.core5.http.ParseException in project httpcomponents-core by apache.

the class ChunkDecoder method processFooters.

private void processFooters() throws IOException {
    final int count = this.trailerBufs.size();
    if (count > 0) {
        this.trailers.clear();
        for (int i = 0; i < this.trailerBufs.size(); i++) {
            try {
                this.trailers.add(new BufferedHeader(this.trailerBufs.get(i)));
            } catch (final ParseException ex) {
                throw new IOException(ex);
            }
        }
    }
    this.trailerBufs.clear();
}
Also used : BufferedHeader(org.apache.hc.core5.http.message.BufferedHeader) ParseException(org.apache.hc.core5.http.ParseException) IOException(java.io.IOException)

Example 4 with ParseException

use of org.apache.hc.core5.http.ParseException in project httpcomponents-core by apache.

the class TlsVersionParser method parse.

ProtocolVersion parse(final CharSequence buffer, final Tokenizer.Cursor cursor, final BitSet delimiters) throws ParseException {
    final int lowerBound = cursor.getLowerBound();
    final int upperBound = cursor.getUpperBound();
    int pos = cursor.getPos();
    if (pos + 4 > cursor.getUpperBound()) {
        throw new ParseException("Invalid TLS protocol version", buffer, lowerBound, upperBound, pos);
    }
    if (buffer.charAt(pos) != 'T' || buffer.charAt(pos + 1) != 'L' || buffer.charAt(pos + 2) != 'S' || buffer.charAt(pos + 3) != 'v') {
        throw new ParseException("Invalid TLS protocol version", buffer, lowerBound, upperBound, pos);
    }
    pos = pos + 4;
    cursor.updatePos(pos);
    if (cursor.atEnd()) {
        throw new ParseException("Invalid TLS version", buffer, lowerBound, upperBound, pos);
    }
    final String s = this.tokenizer.parseToken(buffer, cursor, delimiters);
    final int idx = s.indexOf('.');
    if (idx == -1) {
        final int major;
        try {
            major = Integer.parseInt(s);
        } catch (final NumberFormatException e) {
            throw new ParseException("Invalid TLS major version", buffer, lowerBound, upperBound, pos);
        }
        return new ProtocolVersion("TLS", major, 0);
    } else {
        final String s1 = s.substring(0, idx);
        final int major;
        try {
            major = Integer.parseInt(s1);
        } catch (final NumberFormatException e) {
            throw new ParseException("Invalid TLS major version", buffer, lowerBound, upperBound, pos);
        }
        final String s2 = s.substring(idx + 1);
        final int minor;
        try {
            minor = Integer.parseInt(s2);
        } catch (final NumberFormatException e) {
            throw new ParseException("Invalid TLS minor version", buffer, lowerBound, upperBound, pos);
        }
        return new ProtocolVersion("TLS", major, minor);
    }
}
Also used : ParseException(org.apache.hc.core5.http.ParseException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 5 with ParseException

use of org.apache.hc.core5.http.ParseException in project httpcomponents-core by apache.

the class EntityUtils method toString.

/**
 * Gets the entity content as a String, using the provided default character set
 * if none is found in the entity.
 * If defaultCharset is null, the default "ISO-8859-1" is used.
 *
 * @param entity must not be null
 * @param defaultCharset character set to be applied if none found in the entity,
 * or if the entity provided charset is invalid or not available.
 * @param maxResultLength
 *            The maximum size of the String to return; use it to guard against unreasonable or malicious processing.
 * @return the entity content as a String. May be null if
 *   {@link HttpEntity#getContent()} is null.
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null or if content length &gt; Integer.MAX_VALUE
 * @throws IOException if an error occurs reading the input stream
 * @throws java.nio.charset.UnsupportedCharsetException Thrown when the named entity's charset is not available in
 * this instance of the Java virtual machine and no defaultCharset is provided.
 */
public static String toString(final HttpEntity entity, final Charset defaultCharset, final int maxResultLength) throws IOException, ParseException {
    Args.notNull(entity, "HttpEntity");
    ContentType contentType = null;
    try {
        contentType = ContentType.parse(entity.getContentType());
    } catch (final UnsupportedCharsetException ex) {
        if (defaultCharset == null) {
            throw new UnsupportedEncodingException(ex.getMessage());
        }
    }
    if (contentType != null) {
        if (contentType.getCharset() == null) {
            contentType = contentType.withCharset(defaultCharset);
        }
    } else {
        contentType = ContentType.DEFAULT_TEXT.withCharset(defaultCharset);
    }
    return toString(entity, contentType, maxResultLength);
}
Also used : ContentType(org.apache.hc.core5.http.ContentType) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

ParseException (org.apache.hc.core5.http.ParseException)62 IOException (java.io.IOException)54 SpotifyWebApiException (se.michaelthelin.spotify.exceptions.SpotifyWebApiException)33 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)24 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)13 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)12 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)11 HttpEntity (org.apache.hc.core5.http.HttpEntity)10 HashMap (java.util.HashMap)8 Map (java.util.Map)6 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)6 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)6 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)5 ArrayList (java.util.ArrayList)5 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)5 Matcher (java.util.regex.Matcher)4 UrlEncodedFormEntity (org.apache.hc.client5.http.entity.UrlEncodedFormEntity)4 AuthorizationCodeCredentials (se.michaelthelin.spotify.model_objects.credentials.AuthorizationCodeCredentials)4 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)3 List (java.util.List)3