Search in sources :

Example 6 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)

Example 7 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project ribbon by Netflix.

the class NFHttpClientTest method testNFHttpClient.

@Test
public void testNFHttpClient() throws Exception {
    NFHttpClient client = NFHttpClientFactory.getNFHttpClient("localhost", server.getServerPort());
    ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager();
    cm.setDefaultMaxPerRoute(10);
    HttpGet get = new HttpGet(server.getServerURI());
    ResponseHandler<Integer> respHandler = new ResponseHandler<Integer>() {

        public Integer handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            HttpEntity entity = response.getEntity();
            String contentStr = EntityUtils.toString(entity);
            return contentStr.length();
        }
    };
    long contentLen = client.execute(get, respHandler);
    assertTrue(contentLen > 0);
}
Also used : ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 8 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 9 with ResponseHandler

use of org.apache.http.client.ResponseHandler in project ats-framework by Axway.

the class HttpClient method execute.

/**
     * Main execute method that sends request and receives response.
     *
     * @param method The POST/PUT etc. method
     * @return The response
     * @throws HttpException
     */
private HttpResponse execute(HttpRequestBase httpMethod) throws HttpException {
    HttpClientContext localContext = null;
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        // Add this interceptor to get the values of all HTTP headers in the request.
        // Some of them are provided by the user while others are generated by Apache HTTP Components.
        httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {

            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                Header[] requestHeaders = request.getAllHeaders();
                actualRequestHeaders = new ArrayList<HttpHeader>();
                for (Header header : requestHeaders) {
                    addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
                }
                if (debugLevel != HttpDebugLevel.NONE) {
                    logHTTPRequest(requestHeaders, request);
                }
            }
        });
        // Setup authentication
        if (!StringUtils.isNullOrEmpty(username)) {
            localContext = setupAuthentication(httpClientBuilder);
        }
        // Setup SSL
        if (url.toLowerCase().startsWith("https")) {
            setupSSL(httpClientBuilder);
        }
        // all important options are set, now build the HTTP client
        if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {
            HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST, Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            httpClient = httpClientBuilder.setRoutePlanner(routePlanner).build();
        } else {
            httpClient = httpClientBuilder.build();
        }
    }
    // Setup read and connect timeouts
    httpMethod.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutSeconds * 1000).setConnectTimeout(connectTimeoutSeconds * 1000).build());
    // Add HTTP headers
    addHeadersToHttpMethod(httpMethod);
    // Create response handler
    ResponseHandler<HttpResponse> responseHandler = new ResponseHandler<HttpResponse>() {

        @Override
        public HttpResponse handleResponse(final org.apache.http.HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            Header[] responseHeaders = response.getAllHeaders();
            List<HttpHeader> responseHeadersList = new ArrayList<HttpHeader>();
            for (Header header : responseHeaders) {
                addHeaderToList(responseHeadersList, header.getName(), header.getValue());
            }
            if ((debugLevel & HttpDebugLevel.HEADERS) == HttpDebugLevel.HEADERS) {
                logHTTPResponse(responseHeaders, response);
            }
            try {
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    // No response body, generally have '204 No content' status
                    return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
                } else {
                    if (responseBodyFilePath != null) {
                        FileOutputStream fos = null;
                        try {
                            fos = new FileOutputStream(new File(responseBodyFilePath), false);
                            entity.writeTo(fos);
                        } finally {
                            IoUtils.closeStream(fos);
                        }
                        return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
                    } else {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        entity.writeTo(bos);
                        return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList, bos.toByteArray());
                    }
                }
            } finally {
                if (response instanceof CloseableHttpResponse) {
                    IoUtils.closeStream((CloseableHttpResponse) response, "Failed to close HttpResponse");
                }
            }
        }
    };
    // Send the request as POST/GET etc. and return response.
    try {
        return httpClient.execute(httpMethod, responseHandler, localContext);
    } catch (IOException e) {
        throw new HttpException("Exception occurred sending message to URL '" + actualUrl + "' with a read timeout of " + readTimeoutSeconds + " seconds and a connect timeout of " + connectTimeoutSeconds + " seconds.", e);
    } finally {
        // clear internal variables
        ActionLibraryConfigurator actionLibraryConfigurator = ActionLibraryConfigurator.getInstance();
        if (!actionLibraryConfigurator.getHttpKeepRequestHeaders()) {
            this.requestHeaders.clear();
        }
        if (!actionLibraryConfigurator.getHttpKeepRequestParameters()) {
            this.requestParameters.clear();
        }
        if (!actionLibraryConfigurator.getHttpKeepRequestBody()) {
            this.requestBody = null;
        }
        this.responseBodyFilePath = null;
    }
}
Also used : ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) ActionLibraryConfigurator(com.axway.ats.action.ActionLibraryConfigurator) ArrayList(java.util.ArrayList) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpRequest(org.apache.http.HttpRequest) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Header(org.apache.http.Header) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 10 with ResponseHandler

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

the class TestJSONInterface method httpUrlOverJSONExecute.

private static String httpUrlOverJSONExecute(String method, String url, String user, String password, String scheme, int expectedCode, String expectedCt, String varString) throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> 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 hb = HttpClientBuilder.create();
    hb.setSslcontext(sslContext);
    hb.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = hb.build()) {
        HttpRequestBase request;
        switch(method) {
            case "POST":
                HttpPost post = new HttpPost(url);
                post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = post;
                break;
            case "PUT":
                HttpPut put = new HttpPut(url);
                put.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = put;
                break;
            case "DELETE":
                HttpDelete delete = new HttpDelete(url);
                request = delete;
                break;
            case "GET":
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
            default:
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
        }
        // 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();
        request.setProtocolVersion(HttpVersion.HTTP_1_1);
        request.setConfig(rc);
        if (user != null && password != null) {
            if (scheme.equalsIgnoreCase("hashed")) {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("hashed256")) {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("basic")) {
                request.setHeader("Authorization", "Basic " + new String(Base64.encodeToString(new String(user + ":" + password).getBytes(), false)));
            }
        }
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                String ct = response.getHeaders("Content-Type")[0].getValue();
                if (expectedCt != null) {
                    assertTrue(ct.contains(expectedCt));
                }
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || HANDLED_CLIENT_ERRORS.contains(status)) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(request, rh);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) MessageDigest(java.security.MessageDigest) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

HttpEntity (org.apache.http.HttpEntity)13 ResponseHandler (org.apache.http.client.ResponseHandler)13 HttpResponse (org.apache.http.HttpResponse)10 HttpPost (org.apache.http.client.methods.HttpPost)8 StringEntity (org.apache.http.entity.StringEntity)7 BufferedReader (java.io.BufferedReader)5 InputStreamReader (java.io.InputStreamReader)5 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 HttpGet (org.apache.http.client.methods.HttpGet)4 IOException (java.io.IOException)3 URI (java.net.URI)3 SSLContext (javax.net.ssl.SSLContext)3 Header (org.apache.http.Header)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Serializable (java.io.Serializable)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 HttpHost (org.apache.http.HttpHost)2 HttpRequest (org.apache.http.HttpRequest)2 HttpClient (org.apache.http.client.HttpClient)2