Example usage for org.apache.http.message BasicHttpRequest BasicHttpRequest

List of usage examples for org.apache.http.message BasicHttpRequest BasicHttpRequest

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpRequest BasicHttpRequest.

Prototype

public BasicHttpRequest(String str, String str2) 

Source Link

Usage

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri,
        HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
        InputStream requestEntity) throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    HttpRequest httpRequest;//w  w  w  .  j  av  a 2  s. c  o m
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }
    try {
        httpRequest.setHeaders(convertHeaders(headers));
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        RequestContext.getCurrentContext().set("zuulResponse", zuulResponse);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

private boolean isAlreadyRegistered(RegistrationRequest node) {

    HttpClient client = httpClientFactory.getHttpClient();
    try {/*  ww  w  .j  av a2s.co m*/
        String tmp = "http://" + node.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
                + node.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/proxy";
        URL api = new URL(tmp);
        HttpHost host = new HttpHost(api.getHost(), api.getPort());

        String id = (String) node.getConfiguration().get(RegistrationRequest.ID);
        if (id == null) {
            id = (String) node.getConfiguration().get(RegistrationRequest.REMOTE_HOST);
        }
        BasicHttpRequest r = new BasicHttpRequest("GET", api.toExternalForm() + "?id=" + id);

        HttpResponse response = client.execute(host, r);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new GridException("Hub is down or not responding.");
        }
        JSONObject o = extractObject(response);
        return (Boolean) o.get("success");
    } catch (Exception e) {
        throw new GridException("Hub is down or not responding: " + e.getMessage());
    }
}

From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java

protected HttpRequest buildHttpRequest(String verb, String uri, InputStreamEntity entity,
        MultiValueMap<String, String> headers, MultiValueMap<String, String> params) {
    HttpRequest httpRequest;//from   w w  w. java 2 s . c  o m

    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    case "DELETE":
        BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(verb,
                uri + this.helper.getQueryString(params));
        httpRequest = entityRequest;
        entityRequest.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }

    httpRequest.setHeaders(convertHeaders(headers));
    return httpRequest;
}

From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // initialize request attributes from caches if unset by a subclass by
    // this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }//  ww w .ja v a  2  s . c  om
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not sure it
    // would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;
    // spec: RFC 2616, sec 4.3: either of these two headers signal that
    // there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        // note: we don't bother ensuring we close the servletInputStream
        // since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    //debugProxyRequest(proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            // the response is already "committed" now without any body to
            // send
            // TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is
        // deprecated but it's the only way to pass the
        // reason along too.
        // noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        // abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        // noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is
        // released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        // Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:name.persistent.behaviours.PURLSupport.java

private HttpResponse getFinalResponse(String url, Set<String> via) throws IOException {
    HTTPObjectClient client = HTTPObjectClient.getInstance();
    BasicHttpRequest req = new BasicHttpRequest("GET", url);
    StringBuilder sb = new StringBuilder();
    for (String v : via) {
        if (v.contains(VIA) && (v.endsWith(VIA) || v.contains(VIA + ",")))
            throw new InternalServerError("Request Loop Detected\n" + via + "\n" + VIA);
        if (sb.length() > 0) {
            sb.append(",");
        }/*w  ww . java  2  s .com*/
        sb.append(v);
    }
    sb.append(VIA);
    req.setHeader("Via", sb.toString());
    HttpResponse bd = client.service(req);
    int code = bd.getStatusLine().getStatusCode();
    if (code >= 300 && code < 400) {
        HttpEntity entity = bd.getEntity();
        if (entity != null) {
            entity.consumeContent();
        }
        if (bd.containsHeader("Location")) {
            String loc = bd.getFirstHeader("Location").getValue();
            return getFinalResponse(loc, via);
        }
        String msg = bd.getStatusLine().getReasonPhrase();
        return new BasicHttpResponse(HTTP11, 502, msg);
    }
    return bd;
}

From source file:name.persistent.behaviours.ValidatingDomainSupport.java

private Map<URI, Integer> resolveTargets(List<Value> targets) throws IOException {
    Map<URI, Integer> codes = new LinkedHashMap<URI, Integer>();
    HTTPObjectClient client = HTTPObjectClient.getInstance();
    for (Value target : targets) {
        String url = target.stringValue();
        if (!codes.containsKey(target) && target instanceof URI) {
            HttpRequest request = new BasicHttpRequest("HEAD", url);
            HttpResponse resp = client.service(request);
            try {
                int code = resp.getStatusLine().getStatusCode();
                codes.put((URI) target, code);
            } finally {
                HttpEntity entity = resp.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }/*ww w.j a va2  s .  c om*/
            }
        }
    }
    return codes;
}

From source file:com.fuseim.webapp.ProxyServlet.java

protected HttpRequest initProxyRequest(HttpServletRequest servletRequest, String method, String proxyRequestUri)
        throws IOException {
    HttpRequest proxyRequest; //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest);
    } else {//from w w  w.j  a v a  2  s .  c  o  m
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }
    return proxyRequest;
}

From source file:org.apache.sling.testing.clients.AbstractSlingClient.java

/**
 * <p>Executes a raw HTTP request, WITHOUT consuming the entity in the response. The caller is responsible for consuming the entity or
 * closing the response's InputStream in order to release the connection.
 * Otherwise, the client might run out of connections and will block</p>
 *
 * <p><b>Use this with caution and only if necessary for custom methods or for paths that must not be encoded</b>,
 * otherwise use the safe method {@link #doRequest(HttpUriRequest, List, int...)}</p>
 *
 * <p>It behaves as {@link #doStreamRequest(HttpUriRequest, List, int...)}, so the entity is not consumed.</p>
 * <p>Adds the headers and checks the response against expected status</p>
 *
 * @param method the request to be executed
 * @param uri the uri to be sent as it is (will not prepend the context path)
 * @param headers optional headers to be added to the request
 * @param expectedStatus if passed, the response status is checked against it/them, and has to match at least one of them
 * @return the response, with the entity not consumed
 * @throws ClientException if the request could not be executed
 */// w w w.ja  va 2s .  c  om
public SlingHttpResponse doRawRequest(String method, String uri, List<Header> headers, int... expectedStatus)
        throws ClientException {
    // create context from config
    HttpClientContext context = createHttpClientContextFromConfig();

    HttpHost host = new HttpHost(getUrl().getHost(), getUrl().getPort(), getUrl().getScheme());
    HttpRequest request = new BasicHttpRequest(method, uri);

    // add headers
    if (headers != null) {
        request.setHeaders(headers.toArray(new Header[headers.size()]));
    }

    try {
        log.debug("request {} {}", method, uri);
        SlingHttpResponse response = new SlingHttpResponse(this.execute(host, request, context));
        log.debug("response {}", HttpUtils.getHttpStatus(response));
        // Check the status and throw a ClientException if it doesn't match expectedStatus, but close the entity before
        if (expectedStatus != null && expectedStatus.length > 0) {
            try {
                HttpUtils.verifyHttpStatus(response, expectedStatus);
            } catch (ClientException e) {
                // catch the exception to make sure we close the entity before re-throwing it
                response.close();
                throw e;
            }
        }

        return response;
    } catch (IOException e) {
        throw new ClientException("Could not execute http request", e);
    }
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

/**
 * Opens the connection to a http server or proxy.
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *///from   ww  w . jav a  2s.  c o  m
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    synchronized (HttpsConnection.class) {
        initializeEngine(null, req);
    }
    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());

            // add all 'proxy' headers from the original request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) {
                    proxyReq.addHeader(h);
                }
            }

            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();

            // it is possible to receive informational status
            // codes prior to receiving actual headers;
            // all those status codes are smaller than OK 200
            // 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();

            // here, we return null to indicate that the original
            // 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();

            sslSock.setSoTimeout(SOCKET_TIMEOUT);
            sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()));
        } 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) {
        // handleSslErrorRequest may immediately unsuspend if it wants to
        // allow the certificate anyway.
        // So we mark the connection as suspended, call handleSslErrorRequest
        // then check if we're still suspended and only wait if we actually
        // 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;
}