Search in sources :

Example 31 with ProtocolVersion

use of org.apache.http.ProtocolVersion in project dropwizard by dropwizard.

the class DropwizardApacheConnectorTest method multiple_headers_with_the_same_name_are_processed_successfully.

@Test
public void multiple_headers_with_the_same_name_are_processed_successfully() throws Exception {
    final CloseableHttpClient client = mock(CloseableHttpClient.class);
    final DropwizardApacheConnector dropwizardApacheConnector = new DropwizardApacheConnector(client, null, false);
    final Header[] apacheHeaders = { new BasicHeader("Set-Cookie", "test1"), new BasicHeader("Set-Cookie", "test2") };
    final CloseableHttpResponse apacheResponse = mock(CloseableHttpResponse.class);
    when(apacheResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(apacheResponse.getAllHeaders()).thenReturn(apacheHeaders);
    when(client.execute(Mockito.any())).thenReturn(apacheResponse);
    final ClientRequest jerseyRequest = mock(ClientRequest.class);
    when(jerseyRequest.getUri()).thenReturn(URI.create("http://localhost"));
    when(jerseyRequest.getMethod()).thenReturn("GET");
    when(jerseyRequest.getHeaders()).thenReturn(new MultivaluedHashMap<>());
    final ClientResponse jerseyResponse = dropwizardApacheConnector.apply(jerseyRequest);
    assertThat(jerseyResponse.getStatus()).isEqualTo(apacheResponse.getStatusLine().getStatusCode());
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion) BasicHeader(org.apache.http.message.BasicHeader) ClientRequest(org.glassfish.jersey.client.ClientRequest) BasicStatusLine(org.apache.http.message.BasicStatusLine) Test(org.junit.Test)

Example 32 with ProtocolVersion

use of org.apache.http.ProtocolVersion in project SimplifyReader by chentao0707.

the class HurlStack method performRequest.

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpURLConnection(java.net.HttpURLConnection) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) List(java.util.List) BasicHeader(org.apache.http.message.BasicHeader)

Example 33 with ProtocolVersion

use of org.apache.http.ProtocolVersion in project saga-android by AnandChowdhary.

the class HurlStack method performRequest.

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpURLConnection(java.net.HttpURLConnection) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) List(java.util.List) BasicHeader(org.apache.http.message.BasicHeader)

Example 34 with ProtocolVersion

use of org.apache.http.ProtocolVersion in project platform_external_apache-http by android.

the class HttpRequestExecutor method doSendRequest.

/**
     * Send a request over a connection.
     * This method also handles the expect-continue handshake if necessary.
     * If it does not have to handle an expect-continue handshake, it will
     * not use the connection for reading or anything else that depends on
     * data coming in over the connection.
     *
     * @param request   the request to send, already
     *                  {@link #preProcess preprocessed}
     * @param conn      the connection over which to send the request,
     *                  already established
     * @param context   the context for sending the request
     *
     * @return  a terminal response received as part of an expect-continue
     *          handshake, or
     *          <code>null</code> if the expect-continue handshake is not used
     *
     * @throws HttpException      in case of a protocol or processing problem
     * @throws IOException        in case of an I/O problem
     */
protected HttpResponse doSendRequest(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (conn == null) {
        throw new IllegalArgumentException("HTTP connection may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }
    HttpResponse response = null;
    context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.FALSE);
    conn.sendRequestHeader(request);
    if (request instanceof HttpEntityEnclosingRequest) {
        // Check for expect-continue handshake. We have to flush the
        // headers and wait for an 100-continue response to handle it.
        // If we get a different response, we must not send the entity.
        boolean sendentity = true;
        final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
        if (((HttpEntityEnclosingRequest) request).expectContinue() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
            conn.flush();
            // As suggested by RFC 2616 section 8.2.3, we don't wait for a
            // 100-continue response forever. On timeout, send the entity.
            int tms = request.getParams().getIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 2000);
            if (conn.isResponseAvailable(tms)) {
                response = conn.receiveResponseHeader();
                if (canResponseHaveBody(request, response)) {
                    conn.receiveResponseEntity(response);
                }
                int status = response.getStatusLine().getStatusCode();
                if (status < 200) {
                    if (status != HttpStatus.SC_CONTINUE) {
                        throw new ProtocolException("Unexpected response: " + response.getStatusLine());
                    }
                    // discard 100-continue
                    response = null;
                } else {
                    sendentity = false;
                }
            }
        }
        if (sendentity) {
            conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
        }
    }
    conn.flush();
    context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.TRUE);
    return response;
}
Also used : ProtocolException(java.net.ProtocolException) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HttpResponse(org.apache.http.HttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion)

Example 35 with ProtocolVersion

use of org.apache.http.ProtocolVersion in project platform_external_apache-http by android.

the class BasicLineParser method parseStatusLine.

// non-javadoc, see interface LineParser
public StatusLine parseStatusLine(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 {
        // handle the HTTP-Version
        ProtocolVersion ver = parseProtocolVersion(buffer, cursor);
        // handle the Status-Code
        skipWhitespace(buffer, cursor);
        int i = cursor.getPos();
        int blank = buffer.indexOf(' ', i, indexTo);
        if (blank < 0) {
            blank = indexTo;
        }
        int statusCode = 0;
        try {
            statusCode = Integer.parseInt(buffer.substringTrimmed(i, blank));
        } catch (NumberFormatException e) {
            throw new ParseException("Unable to parse status code from status line: " + buffer.substring(indexFrom, indexTo));
        }
        //handle the Reason-Phrase
        i = blank;
        String reasonPhrase = null;
        if (i < indexTo) {
            reasonPhrase = buffer.substringTrimmed(i, indexTo);
        } else {
            reasonPhrase = "";
        }
        return createStatusLine(ver, statusCode, reasonPhrase);
    } catch (IndexOutOfBoundsException e) {
        throw new ParseException("Invalid status line: " + buffer.substring(indexFrom, indexTo));
    }
}
Also used : ParseException(org.apache.http.ParseException) ProtocolVersion(org.apache.http.ProtocolVersion)

Aggregations

ProtocolVersion (org.apache.http.ProtocolVersion)113 BasicStatusLine (org.apache.http.message.BasicStatusLine)54 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)43 StatusLine (org.apache.http.StatusLine)42 Test (org.junit.Test)33 Header (org.apache.http.Header)26 HttpEntity (org.apache.http.HttpEntity)26 HttpResponse (org.apache.http.HttpResponse)22 StringEntity (org.apache.http.entity.StringEntity)20 URL (java.net.URL)16 BasicHeader (org.apache.http.message.BasicHeader)16 IOException (java.io.IOException)15 HttpURLConnection (java.net.HttpURLConnection)15 List (java.util.List)15 HashMap (java.util.HashMap)14 HttpHost (org.apache.http.HttpHost)12 ParseException (org.apache.http.ParseException)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11 MockHttpStack (com.android.volley.mock.MockHttpStack)10 HttpRequest (org.apache.http.HttpRequest)10