Search in sources :

Example 6 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project iosched by google.

the class MockHttpClient method execute.

// This is the only one we actually use.
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) {
    requestExecuted = request;
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), mStatusCode, "");
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(mResponseEntity);
    return response;
}
Also used : BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine)

Example 7 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project robovm by robovm.

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)

Example 8 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project robovm by robovm.

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 9 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project robovm by robovm.

the class BasicHttpResponse method setStatusCode.

// non-javadoc, see interface HttpResponse
public void setStatusCode(int code) {
    // argument checked in BasicStatusLine constructor
    ProtocolVersion ver = this.statusline.getProtocolVersion();
    this.statusline = new BasicStatusLine(ver, code, getReason(code));
}
Also used : ProtocolVersion(org.apache.http.ProtocolVersion)

Example 10 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project XobotOS by xamarin.

the class SSLConnectionClosedByUserException method openConnection.

/**
     * Opens the connection to a http server or proxy.
     *
     * @return the opened low level connection
     * @throws IOException if the connection fails for any reason.
     */
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;
    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());
            proxySock.setSoTimeout(60 * 1000);
            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);
            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }
            throw new IOException(errorMessage);
        }
        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());
            // 400 Bad Request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive") || headerName.equals("host")) {
                    proxyReq.addHeader(h);
                }
            }
            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        }
        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }
                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();
            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();
            proxyConnection.close();
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
            sslSock.setSoTimeout(SOCKET_TIMEOUT);
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }
            throw new IOException(errorMessage);
        }
    }
    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());
    // Inform the user if there is a problem
    if (error != null) {
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }
    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);
    return conn;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) StatusLine(org.apache.http.StatusLine) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpException(org.apache.http.HttpException) ParseException(org.apache.http.ParseException) BasicHttpParams(org.apache.http.params.BasicHttpParams) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Aggregations

ProtocolVersion (org.apache.http.ProtocolVersion)143 BasicStatusLine (org.apache.http.message.BasicStatusLine)67 Test (org.junit.Test)53 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)50 StatusLine (org.apache.http.StatusLine)44 HttpResponse (org.apache.http.HttpResponse)32 HttpEntity (org.apache.http.HttpEntity)31 Header (org.apache.http.Header)25 StringEntity (org.apache.http.entity.StringEntity)25 IOException (java.io.IOException)18 BasicHeader (org.apache.http.message.BasicHeader)15 URL (java.net.URL)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 HttpURLConnection (java.net.HttpURLConnection)13 HashMap (java.util.HashMap)13 List (java.util.List)13 ParseException (org.apache.http.ParseException)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HttpHost (org.apache.http.HttpHost)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11