Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients createDefault.

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:core.VirusTotalAPIHelper.java

public static CloseableHttpResponse scanFile(File fileToScan) {
    if (apiKey == null || apiKey.isEmpty()) {
        return null;
    }//from   w  ww  .  j a  v  a2s .c  om
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/scan");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("apikey", apiKey);
        builder.addBinaryBody("file", fileToScan, ContentType.APPLICATION_OCTET_STREAM, fileToScan.getName());
        HttpEntity multipart = builder.build();
        httpsScanFilePost.setEntity(multipart);

        CloseableHttpResponse response = client.execute(httpsScanFilePost);
        return response;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}

From source file:net.GoTicketing.GetNecessaryCookie.java

public static void getCookie(String host, String referer, String target, Map<String, String> cookieMap) {

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(host + target);
        httpGet.setConfig(DEFAULT_PARAMS);

        String cookies = CookieMapToString(cookieMap);
        if (!cookies.equals(""))
            httpGet.setHeader("Cookie", cookies);

        httpGet.setHeader("Referer", host + referer);

        try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {

            //  HttpStatusCode != 200 && != 404
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                    && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
                String ErrorCode = "Response Status : " + httpResponse.getStatusLine().getStatusCode();
                throw new IOException(ErrorCode);
            }//www.java2s  .com

            try (BufferedInputStream buff = new BufferedInputStream(httpResponse.getEntity().getContent())) {
                String hstr;
                for (Header header : httpResponse.getHeaders("Set-Cookie")) {
                    hstr = header.getValue().split(";")[0];
                    cookieMap.put(hstr.split("=", 2)[0], hstr.split("=", 2)[1]);
                }
            }
        }
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Get cookie from {0} failed in exception : {1}", new Object[] { target, ex });
    }
}

From source file:pt.isel.mpd.util.HttpGw.java

public static <T> T getData(String path, HttpRespFormatter<T> formatter) {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        /*//from w  w w.  ja v a2 s  .c  om
        * Method: HttpGet
        */
        HttpGet httpget = new HttpGet(path);
        /*
        * HttpResponse
        */
        try (CloseableHttpResponse response = httpclient.execute(httpget)) {

            return formatter.format(response.getEntity());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:email.mandrill.SendMail.java

public static MessageResponses sendMail(Message message) {
    try {/*from w  ww.j a  v  a  2s .com*/
        logger.log(Level.INFO, "Message:" + message.toJSONString());

        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("https://mandrillapp.com/api/1.0/messages/send.json");

        String request = message.toJSONString();
        HttpEntity entity = new ByteArrayEntity(request.getBytes("UTF-8"));
        httppost.setEntity(entity);
        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            InputStream instream = responseEntity.getContent();
            try {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                String theString = writer.toString();

                MessageResponses messageResponses = new MessageResponses(theString);
                //Do whateveer is needed with the response.
                logger.log(Level.INFO, theString);
                return messageResponses;
            } finally {
                instream.close();
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception while updating org name:", null));
    }
    return null;
}

From source file:org.moneta.utils.RestTestingUtils.java

public static HttpResponse simpleRESTGet(String requestUri) {
    Validate.notEmpty(requestUri, "Null or blank requestUri not allowed.");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(requestUri);
    try {//from   ww w  .j ava2 s.c o  m
        return httpclient.execute(httpGet);
    } catch (Exception e) {
        throw new ContextedRuntimeException(e).addContextValue("requestUri", requestUri);
    }
}

From source file:cat.calidos.morfeu.utils.injection.HttpClientModule.java

@Provides
public static CloseableHttpClient produceHttpClient() {
    return HttpClients.createDefault();
}

From source file:org.fcrepo.camel.indexing.solr.integration.TestUtils.java

public static InputStream httpGet(final String url) throws Exception {
    final CloseableHttpClient httpClient = HttpClients.createDefault();
    final HttpGet get = new HttpGet(url);
    return httpClient.execute(get).getEntity().getContent();
}

From source file:org.mobile.mpos.util.HttpClientHelper.java

/**
 * get request/*from ww w .j  av a2 s.  co m*/
 * @param uri
 * @return
 */
public static String get(String uri) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(uri);
        log.info("Executing request " + httpget.getRequestLine());
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpClient.execute(httpget, responseHandler);
        log.info(" response " + responseBody);
        return responseBody;
    } catch (ClientProtocolException e) {
        log.error("ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        log.error("IOException " + e.getMessage());
    } finally {
        close(httpClient);
    }
    return null;
}

From source file:com.tellapart.taba.TabaApiFactory.java

public static synchronized void initialize(TabaClientProperties properties) {
    Preconditions.checkState(engine == null, "Already initialized.");

    TabaClientEngine clientEngine = new DefaultClientEngine(properties, HttpClients.createDefault(),
            Executors.newScheduledThreadPool(1));

    initialize(clientEngine);//w  ww .j a  v a2s. c  o  m
}

From source file:jon.javaadapter.JavaAdapterResource.java

public static void init() {
    client = HttpClients.createDefault();
    host = new HttpHost("developer.ibm.com");
}