Search in sources :

Example 21 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project OsmAnd-tools by osmandapp.

the class ReportsController method btcRpcCall.

private Object btcRpcCall(String method, Object... pms) throws UnsupportedEncodingException, IOException, ClientProtocolException {
    HttpPost httppost = new HttpPost("http://" + btcJsonRpcUser + ":" + btcJsonRpcPwd + "@127.0.0.1:8332/");
    httppost.setConfig(requestConfig);
    httppost.addHeader("charset", StandardCharsets.UTF_8.name());
    Map<String, Object> params = new HashMap<>();
    params.put("jsonrpc", "1.0");
    params.put("id", "server");
    params.put("method", method);
    if (pms != null && pms.length > 0) {
        params.put("params", Arrays.asList(pms));
    }
    StringEntity entity = new StringEntity(formatter.toJson(params));
    LOGGER.info("Btc rpc send with content: " + formatter.toJson(params));
    httppost.setEntity(entity);
    try (CloseableHttpResponse response = httpclient.execute(httppost)) {
        HttpEntity ht = response.getEntity();
        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String result = EntityUtils.toString(buf, StandardCharsets.UTF_8);
        Map<?, ?> res = formatter.fromJson(new JsonReader(new StringReader(result)), Map.class);
        LOGGER.info("Result: " + result);
        if (res.get("result") != null) {
            return res.get("result");
        } else {
            return null;
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) StringReader(java.io.StringReader) JsonReader(com.google.gson.stream.JsonReader)

Example 22 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project jersey by jersey.

the class ApacheConnector method getHttpEntity.

private HttpEntity getHttpEntity(final ClientRequest clientRequest, final boolean bufferingEnabled) {
    final Object entity = clientRequest.getEntity();
    if (entity == null) {
        return null;
    }
    final AbstractHttpEntity httpEntity = new AbstractHttpEntity() {

        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public long getContentLength() {
            return -1;
        }

        @Override
        public InputStream getContent() throws IOException, IllegalStateException {
            if (bufferingEnabled) {
                final ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
                writeTo(buffer);
                return new ByteArrayInputStream(buffer.toByteArray());
            } else {
                return null;
            }
        }

        @Override
        public void writeTo(final OutputStream outputStream) throws IOException {
            clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(final int contentLength) throws IOException {
                    return outputStream;
                }
            });
            clientRequest.writeEntity();
        }

        @Override
        public boolean isStreaming() {
            return false;
        }
    };
    if (bufferingEnabled) {
        try {
            return new BufferedHttpEntity(httpEntity);
        } catch (final IOException e) {
            throw new ProcessingException(LocalizationMessages.ERROR_BUFFERING_ENTITY(), e);
        }
    } else {
        return httpEntity;
    }
}
Also used : BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ChunkedOutputStream(org.apache.http.impl.io.ChunkedOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) ProcessingException(javax.ws.rs.ProcessingException)

Example 23 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project elasticsearch by elastic.

the class RequestLogger method buildTraceResponse.

/**
     * Creates curl output for given response
     */
static String buildTraceResponse(HttpResponse httpResponse) throws IOException {
    String responseLine = "# " + httpResponse.getStatusLine().toString();
    for (Header header : httpResponse.getAllHeaders()) {
        responseLine += "\n# " + header.getName() + ": " + header.getValue();
    }
    responseLine += "\n#";
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        if (entity.isRepeatable() == false) {
            entity = new BufferedHttpEntity(entity);
        }
        httpResponse.setEntity(entity);
        ContentType contentType = ContentType.get(entity);
        Charset charset = StandardCharsets.UTF_8;
        if (contentType != null && contentType.getCharset() != null) {
            charset = contentType.getCharset();
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) {
            String line;
            while ((line = reader.readLine()) != null) {
                responseLine += "\n# " + line;
            }
        }
    }
    return responseLine;
}
Also used : Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ContentType(org.apache.http.entity.ContentType) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Charset(java.nio.charset.Charset)

Example 24 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project elasticsearch by elastic.

the class ResponseException method buildMessage.

private static String buildMessage(Response response) throws IOException {
    String message = response.getRequestLine().getMethod() + " " + response.getHost() + response.getRequestLine().getUri() + ": " + response.getStatusLine().toString();
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        if (entity.isRepeatable() == false) {
            entity = new BufferedHttpEntity(entity);
            response.getHttpResponse().setEntity(entity);
        }
        message += "\n" + EntityUtils.toString(entity);
    }
    return message;
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity)

Example 25 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project XobotOS by xamarin.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
     * Creates a tunnel to the target server.
     * The connection must be established to the (last) proxy.
     * A CONNECT request for tunnelling through the proxy will
     * be created and sent, the response received and checked.
     * This method does <i>not</i> update the connection with
     * information about the tunnel, that is left to the caller.
     *
     * @param route     the route to establish
     * @param context   the context for request execution
     *
     * @return  <code>true</code> if the tunnelled route is secure,
     *          <code>false</code> otherwise.
     *          The implementation here always returns <code>false</code>,
     *          but derived classes may override.
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Aggregations

BufferedHttpEntity (org.apache.http.entity.BufferedHttpEntity)43 HttpEntity (org.apache.http.HttpEntity)31 IOException (java.io.IOException)21 HttpResponse (org.apache.http.HttpResponse)16 HttpGet (org.apache.http.client.methods.HttpGet)11 Header (org.apache.http.Header)9 InputStream (java.io.InputStream)8 HttpClient (org.apache.http.client.HttpClient)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 HttpException (org.apache.http.HttpException)6 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)6 File (java.io.File)5 FileOutputStream (java.io.FileOutputStream)5 URISyntaxException (java.net.URISyntaxException)5 HttpHost (org.apache.http.HttpHost)4 HttpRequest (org.apache.http.HttpRequest)4 StatusLine (org.apache.http.StatusLine)4 AuthenticationException (org.apache.http.auth.AuthenticationException)4 CredentialsProvider (org.apache.http.client.CredentialsProvider)4