Search in sources :

Example 1 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project cas by apereo.

the class SimpleHttpClient method sendMessageToEndPoint.

@Override
public boolean sendMessageToEndPoint(final HttpMessage message) {
    Assert.notNull(this.httpClient);
    try {
        final HttpPost request = new HttpPost(message.getUrl().toURI());
        request.addHeader("Content-Type", message.getContentType());
        final StringEntity entity = new StringEntity(message.getMessage(), ContentType.create(message.getContentType()));
        request.setEntity(entity);
        final ResponseHandler<Boolean> handler = response -> response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
        LOGGER.debug("Created HTTP post message payload [{}]", request);
        final HttpRequestFutureTask<Boolean> task = this.requestExecutorService.execute(request, HttpClientContext.create(), handler);
        if (message.isAsynchronous()) {
            return true;
        }
        return task.get();
    } catch (final RejectedExecutionException e) {
        LOGGER.warn(e.getMessage(), e);
        return false;
    } catch (final Exception e) {
        LOGGER.debug(e.getMessage(), e);
        return false;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestFutureTask(org.apache.http.impl.client.HttpRequestFutureTask) URL(java.net.URL) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) LoggerFactory(org.slf4j.LoggerFactory) HttpStatus(org.apache.http.HttpStatus) EntityUtils(org.apache.http.util.EntityUtils) FutureRequestExecutionService(org.apache.http.impl.client.FutureRequestExecutionService) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Serializable(java.io.Serializable) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) DisposableBean(org.springframework.beans.factory.DisposableBean) ResponseHandler(org.apache.http.client.ResponseHandler) Collections(java.util.Collections) Assert(org.springframework.util.Assert) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) MalformedURLException(java.net.MalformedURLException)

Example 2 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project android_frameworks_base by ParanoidAndroid.

the class FsUtils method getLayoutTestsDirContents.

public static List<String> getLayoutTestsDirContents(String dirRelativePath, boolean recurse, boolean mode) {
    String modeString = (mode ? "folders" : "files");
    URL url = null;
    try {
        url = new URL(SCRIPT_URL + "?path=" + dirRelativePath + "&recurse=" + recurse + "&mode=" + modeString);
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "path=" + dirRelativePath + " recurse=" + recurse + " mode=" + modeString, e);
        return new LinkedList<String>();
    }
    HttpGet httpRequest = new HttpGet(url.toString());
    ResponseHandler<LinkedList<String>> handler = new ResponseHandler<LinkedList<String>>() {

        @Override
        public LinkedList<String> handleResponse(HttpResponse response) throws IOException {
            LinkedList<String> lines = new LinkedList<String>();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return lines;
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return lines;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    lines.add(line);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            return lines;
        }
    };
    try {
        return getHttpClient().execute(httpRequest, handler);
    } catch (IOException e) {
        Log.e(LOG_TAG, "getLayoutTestsDirContents(): HTTP GET failed for URL " + url);
        return null;
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL) LinkedList(java.util.LinkedList) BufferedReader(java.io.BufferedReader)

Example 3 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project voltdb by VoltDB.

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 4 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project LiveSDK-for-Android by liveservices.

the class UploadRequestTest method testSendPathQueryParameterToHttpPut.

/**
     * WinLive 633441: Make sure the query parameters on path get sent to
     * the HTTP PUT part of the upload.
     */
public void testSendPathQueryParameterToHttpPut() throws Throwable {
    JSONObject jsonResponseBody = new JSONObject();
    jsonResponseBody.put(JsonKeys.UPLOAD_LOCATION, "http://test.com/location");
    InputStream responseStream = new ByteArrayInputStream(jsonResponseBody.toString().getBytes());
    MockHttpEntity responseEntity = new MockHttpEntity(responseStream);
    BasicStatusLine ok = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "");
    final MockHttpResponse uploadLocationResponse = new MockHttpResponse(responseEntity, ok);
    HttpClient client = new HttpClient() {

        /** the first request to the client is the upload location request. */
        boolean uploadLocationRequest = true;

        @Override
        public HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException {
            if (uploadLocationRequest) {
                uploadLocationRequest = false;
                return uploadLocationResponse;
            }
            // This is really the only part we care about in this test.
            // That the 2nd request's uri has foo=bar in the query string.
            URI uri = request.getURI();
            assertEquals("foo=bar&overwrite=choosenewname", uri.getQuery());
            // just return the previous reponse.
            return uploadLocationResponse;
        }

        @Override
        public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1, HttpContext arg2) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2, HttpContext arg3) throws IOException, ClientProtocolException {
            throw new UnsupportedOperationException();
        }

        @Override
        public ClientConnectionManager getConnectionManager() {
            throw new UnsupportedOperationException();
        }

        @Override
        public HttpParams getParams() {
            throw new UnsupportedOperationException();
        }
    };
    LiveConnectSession session = TestUtils.newMockLiveConnectSession();
    HttpEntity entity = new MockHttpEntity();
    String path = Paths.ME_SKYDRIVE + "?foo=bar";
    String filename = "filename";
    UploadRequest uploadRequest = new UploadRequest(session, client, path, entity, filename, OverwriteOption.Rename);
    uploadRequest.execute();
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpRequest(org.apache.http.HttpRequest) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) MockHttpEntity(com.microsoft.live.mock.MockHttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpContext(org.apache.http.protocol.HttpContext) MockHttpEntity(com.microsoft.live.mock.MockHttpEntity) URI(java.net.URI) BasicStatusLine(org.apache.http.message.BasicStatusLine) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) MockHttpResponse(com.microsoft.live.mock.MockHttpResponse)

Example 5 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project openhab1-addons by openhab.

the class StreamClientImpl method createResponseHandler.

protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
    return new ResponseHandler<StreamResponseMessage>() {

        @Override
        public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException {
            StatusLine statusLine = httpResponse.getStatusLine();
            log.fine("Received HTTP response: " + statusLine);
            // Status
            UpnpResponse responseOperation = new UpnpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            // Message
            StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation);
            // Headers
            responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse)));
            // Body
            HttpEntity entity = httpResponse.getEntity();
            if (entity == null || entity.getContentLength() == 0) {
                return responseMessage;
            }
            if (responseMessage.isContentTypeMissingOrText()) {
                log.fine("HTTP response message contains text entity");
                responseMessage.setBody(UpnpMessage.BodyType.STRING, EntityUtils.toString(entity));
            } else {
                log.fine("HTTP response message contains binary entity");
                responseMessage.setBody(UpnpMessage.BodyType.BYTES, EntityUtils.toByteArray(entity));
            }
            return responseMessage;
        }
    };
}
Also used : StatusLine(org.apache.http.StatusLine) ResponseHandler(org.apache.http.client.ResponseHandler) UpnpResponse(org.teleal.cling.model.message.UpnpResponse) HttpEntity(org.apache.http.HttpEntity) UpnpHeaders(org.teleal.cling.model.message.UpnpHeaders) StreamResponseMessage(org.teleal.cling.model.message.StreamResponseMessage) HttpResponse(org.apache.http.HttpResponse)

Aggregations

HttpEntity (org.apache.http.HttpEntity)8 ResponseHandler (org.apache.http.client.ResponseHandler)8 HttpResponse (org.apache.http.HttpResponse)5 HttpGet (org.apache.http.client.methods.HttpGet)4 HttpPost (org.apache.http.client.methods.HttpPost)3 StringEntity (org.apache.http.entity.StringEntity)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 URI (java.net.URI)2 URL (java.net.URL)2 SSLContext (javax.net.ssl.SSLContext)2 HttpHost (org.apache.http.HttpHost)2 HttpRequest (org.apache.http.HttpRequest)2 RequestConfig (org.apache.http.client.config.RequestConfig)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)2 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)2 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)2