Search in sources :

Example 66 with HttpResponse

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpResponse 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 67 with HttpResponse

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpResponse in project java-chassis by ServiceComb.

the class HttpsClient method get.

private static HttpResponse get(HttpClient httpClient, String url, Map<String, String> headers) throws ClientProtocolException, IOException {
    HttpGet getRequest = new HttpGet(url);
    for (Entry<String, String> header : headers.entrySet()) {
        getRequest.addHeader(header.getKey(), header.getValue());
    }
    HttpResponse response = httpClient.execute(getRequest);
    return response;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Example 68 with HttpResponse

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpResponse in project java-chassis by ServiceComb.

the class TestHttpsClient method testHttpClient.

@Test
public void testHttpClient() throws ClientProtocolException, IOException {
    // test valid Invalid Inputs
    Map<String, String> oHeaders = new HashMap<String, String>();
    oHeaders.put("X-Auth", "JHGUGJGH");
    HttpResponse oResponse = HttpsClient.execute("UNKNOWN METHOD", oHeaders, "//check", "body", null);
    Assert.assertEquals(null, oResponse);
    oResponse = HttpsClient.execute("", oHeaders, "//check", "body", null);
    Assert.assertEquals(null, oResponse);
    oResponse = HttpsClient.execute("UNKNOWN METHOD", oHeaders, "", "body", null);
    Assert.assertEquals(null, oResponse);
    oResponse = HttpsClient.execute("UNKNOWN METHOD", null, "//check", "body", null);
    Assert.assertEquals(null, oResponse);
    // With default Bean
    HttpsConfigInfoBean oBean = new HttpsConfigInfoBean();
    oBean.setKeyStorePath("JHGJ");
    oBean.setKeyStorePasswd("HJGJH");
    oBean.setTrustStorePasswd("JHGJHG");
    oBean.setTrustStorePath("JHGJGj");
    Assert.assertEquals("JHGJGj", oBean.getTrustStorePath());
    Assert.assertEquals("JHGJHG", oBean.getTrustStorePasswd());
    oResponse = HttpsClient.execute("UNKNOWN METHOD", oHeaders, "//check", "body", oBean);
    Assert.assertEquals(null, oResponse);
    HttpsClient.getHttpsClient(oBean);
    Assert.assertNotEquals(null, HttpsClient.getHttpsClient(Mockito.mock(HttpsConfigInfoBean.class)));
    //Handle Error Scenarios
    try {
        oResponse = HttpsClient.execute("POST", oHeaders, "//check", "body", oBean);
    } catch (Exception e) {
        Assert.assertEquals("Target host is null", e.getMessage());
    }
    try {
        oResponse = HttpsClient.execute("GET", oHeaders, "//check", "body", oBean);
    } catch (Exception e) {
        Assert.assertEquals("Target host is null", e.getMessage());
    }
    try {
        oResponse = HttpsClient.execute("DELETE", oHeaders, "//check", "body", oBean);
    } catch (Exception e) {
        Assert.assertEquals("Target host is null", e.getMessage());
    }
// TODO Check the valid Responses
}
Also used : HashMap(java.util.HashMap) HttpResponse(org.apache.http.HttpResponse) HttpsConfigInfoBean(io.servicecomb.foundation.common.entities.HttpsConfigInfoBean) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Test(org.junit.Test)

Example 69 with HttpResponse

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpResponse in project screenbird by adamhub.

the class FileUtil method postFile.

/**
     * Uploads a file via a POST request to a URL.
     * @param fileLocation  path to the file that will be uploaded
     * @param title         title of the video
     * @param slug          slug of the video 
     * @param description   description of the video
     * @param video_type    format of the video (mp4, mpg, avi, etc.)
     * @param checksum      checksum of the file that will be uploaded
     * @param is_public     publicity settings of the file
     * @param pbUpload      progress bar for the upload
     * @param fileSize      the length, in bytes, of the file to be uploaded
     * @param csrf_token    csrf token for the POST request
     * @param user_id       Screenbird user id of the uploader
     * @param channel_id    Screenbird channel id to where the video will be uploaded to
     * @param an_tok        anonymous token identifier if the uploader is not logged in to Screenbird
     * @param listener      listener for the upload
     * @param upload_url    URL where the POST request will be sent to.
     * @return
     * @throws IOException 
     */
public static String[] postFile(String fileLocation, String title, String slug, String description, String video_type, String checksum, Boolean is_public, final JProgressBar pbUpload, long fileSize, String csrf_token, String user_id, String channel_id, String an_tok, ProgressBarUploadProgressListener listener, String upload_url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(upload_url);
    File file = new File(fileLocation);
    ProgressMultiPartEntity mpEntity = new ProgressMultiPartEntity(listener);
    ContentBody cbFile = new FileBody(file, "video/quicktime");
    mpEntity.addPart("videoupload", cbFile);
    ContentBody cbToken = new StringBody(title);
    mpEntity.addPart("csrfmiddlewaretoken", cbToken);
    ContentBody cbUser_id = new StringBody(user_id);
    mpEntity.addPart("user_id", cbUser_id);
    ContentBody cbChannel_id = new StringBody(channel_id);
    mpEntity.addPart("channel_id", cbChannel_id);
    ContentBody cbAnonym_id = new StringBody(an_tok);
    mpEntity.addPart("an_tok", cbAnonym_id);
    ContentBody cbTitle = new StringBody(title);
    mpEntity.addPart("title", cbTitle);
    ContentBody cbSlug = new StringBody(slug);
    mpEntity.addPart("slug", cbSlug);
    ContentBody cbPublic = new StringBody(is_public ? "1" : "0");
    mpEntity.addPart("is_public", cbPublic);
    ContentBody cbDescription = new StringBody(description);
    mpEntity.addPart("description", cbDescription);
    ContentBody cbChecksum = new StringBody(checksum);
    mpEntity.addPart("checksum", cbChecksum);
    ContentBody cbType = new StringBody(video_type);
    mpEntity.addPart("video_type", cbType);
    httppost.setEntity(mpEntity);
    log("===================================================");
    log("executing request " + httppost.getRequestLine());
    log("===================================================");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    String[] result = new String[2];
    String status = response.getStatusLine().toString();
    result[0] = (status.indexOf("200") >= 0) ? "200" : status;
    log("===================================================");
    log("response " + response.toString());
    log("===================================================");
    if (resEntity != null) {
        result[1] = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);
    }
    httpclient.getConnectionManager().shutdown();
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ContentBody(org.apache.http.entity.mime.content.ContentBody) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) ProgressMultiPartEntity(com.bixly.pastevid.screencap.components.progressbar.ProgressMultiPartEntity) HttpResponse(org.apache.http.HttpResponse) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 70 with HttpResponse

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpResponse in project ats-framework by Axway.

the class HttpClient method processHttpRequest.

/**
     * Perform prepared request and optionally return the response
     * @param httpRequest HttpGet, HttpPost etc
     * @param needResponse do we need the response, if false - then null is returned
     * @return the response from the request as an {@link InputStream} or a {@link String} object
     * @throws FileTransferException
     */
private Object processHttpRequest(HttpUriRequest httpRequest, boolean needResponse, boolean returnAsString) throws FileTransferException {
    HttpEntity responseEntity = null;
    boolean responseNotConsumed = true;
    OutputStream outstream = null;
    String errMsg = "Unable to complete request!";
    String responseAsString = null;
    InputStream responseAsStream = null;
    try {
        // send request
        HttpResponse response = httpClient.execute(httpRequest, httpContext);
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new FileTransferException("Request to '" + httpRequest.getURI() + "' returned " + response.getStatusLine());
        }
        // get the response
        responseEntity = response.getEntity();
        if (!needResponse) {
            responseNotConsumed = true;
        } else {
            if (responseEntity != null) {
                if (!returnAsString) {
                    responseAsStream = responseEntity.getContent();
                } else {
                    int respLengthEstimate = (int) responseEntity.getContentLength();
                    if (respLengthEstimate < 0) {
                        respLengthEstimate = 1024;
                    }
                    outstream = new ByteArrayOutputStream(respLengthEstimate);
                    responseEntity.writeTo(outstream);
                    outstream.flush();
                    responseAsString = outstream.toString();
                }
                responseNotConsumed = false;
            }
        }
    } catch (ClientProtocolException e) {
        log.error(errMsg, e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error(errMsg, e);
        throw new FileTransferException(e);
    } finally {
        if (responseEntity != null && outstream != null) {
            IoUtils.closeStream(outstream);
        }
        if (responseNotConsumed) {
            try {
                // We were not able to properly stream the entity content to the local file system.
                // The next line consumes the entity content closes the underlying stream.
                EntityUtils.consume(responseEntity);
            } catch (IOException e) {
            // we tried our best to release the resources
            }
        }
    }
    log.info("Successfully completed GET request '" + httpRequest.getURI() + "'");
    if (returnAsString) {
        return responseAsString;
    }
    return responseAsStream;
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Aggregations

HttpResponse (org.apache.http.HttpResponse)4366 Test (org.junit.Test)2158 HttpGet (org.apache.http.client.methods.HttpGet)1833 IOException (java.io.IOException)1110 URI (java.net.URI)834 HttpPost (org.apache.http.client.methods.HttpPost)759 HttpClient (org.apache.http.client.HttpClient)600 HttpEntity (org.apache.http.HttpEntity)541 TestHttpClient (io.undertow.testutils.TestHttpClient)403 InputStream (java.io.InputStream)398 Header (org.apache.http.Header)385 StringEntity (org.apache.http.entity.StringEntity)363 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)344 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)338 HttpPut (org.apache.http.client.methods.HttpPut)320 ArrayList (java.util.ArrayList)316 Identity (org.olat.core.id.Identity)262 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)253 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)209 File (java.io.File)196