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:com.palominolabs.crm.sf.rest.TestConnections.java

static HttpApiClient getHttpApiClient(String user, String password) {
    try {//from ww w .  ja  v a 2  s  .co  m
        BindingConfig bindingConfig = getBindingConfig(user, password);
        String host = new URL(bindingConfig.getPartnerServerUrl()).getHost();
        return new HttpApiClient(host, bindingConfig.getSessionId(), MAPPER, HttpClients.createDefault());
    } catch (ApiException e) {
        throw Throwables.propagate(e);
    } catch (MalformedURLException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.eclipse.dirigible.cli.apis.ImportProjectAPI.java

public static void importProject(RequestConfig config, String url, InputStream in, String filename,
        Map<String, String> headers) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addPart(PART_NAME, new InputStreamBody(in, filename));

    HttpPost postRequest = new HttpPost(url);
    postRequest.setEntity(entityBuilder.build());
    addHeaders(postRequest, headers);/*from   w  w  w. j a v a2  s.  c om*/
    if (config != null) {
        postRequest.setConfig(config);
    }
    executeRequest(httpClient, postRequest);
}

From source file:com.turn.ttorrent.common.Utils.java

/**
 * Resolves a file from URI and returns its byte array.
 * //from w  w  w .j ava  2s.  co m
 * @param uri
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static byte[] resolveUrlFileToByteArray(URI uri) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {

        HttpGet get = new HttpGet(uri);
        HttpResponse response = httpclient.execute(get);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream inputStream = entity.getContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, outputStream);
            return outputStream.toByteArray();
        }

        throw new IOException("Could not resolve file... [" + uri + "]");

    } finally {
        httpclient.close();
    }

}

From source file:com.atomiton.watermanagement.ngo.util.HttpRequestResponseHandler.java

public static String sendPost(String serverURL, String postBody) throws Exception {

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(serverURL);

    StringEntity entity = new StringEntity(postBody, "UTF-8");

    post.setEntity(entity);//from  w  ww  .  j a v a  2  s  .  co  m

    HttpResponse response = client.execute(post);
    // System.out.println("\nSending 'POST' request to URL : " + serverURL);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    client.close();
    // System.out.println(result.toString());
    return result.toString();
}

From source file:com.portfolio.data.utils.PostForm.java

public static boolean sendFile(String sessionid, String backend, String user, String uuid, String lang,
        File file) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {//from   w  w w  . j a  v a2  s  .com
        // Server + "/resources/resource/file/" + uuid +"?lang="+ lang
        // "http://"+backend+"/user/"+user+"/file/"+uuid+"/"+lang+"ptype/fs";
        String url = "http://" + backend + "/resources/resource/file/" + uuid + "?lang=" + lang;
        HttpPost post = new HttpPost(url);
        post.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us

        /// Remove import language tag
        String filename = file.getName(); /// NOTE: Since it's used with zip import, specific code.
        int langindex = filename.lastIndexOf("_");
        filename = filename.substring(0, langindex) + filename.substring(langindex + 3);

        FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY, filename); // File from import

        /// Form info
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("uploadfile", bin).build();
        post.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(post);

        /*
        try
        {
           HttpEntity resEntity = response.getEntity();   /// Will be JSON
           if( resEntity != null )
           {
              BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));
              StringBuilder builder = new StringBuilder();
              for( String line = null; (line = reader.readLine()) != null; )
          builder.append(line).append("\n");
                
              updateResource( sessionid, backend, uuid, lang, builder.toString() );
           }
           EntityUtils.consume(resEntity);
        }
        finally
        {
           response.close();
        }
        //*/
    } finally {
        httpclient.close();
    }

    return true;
}

From source file:org.openo.nfvo.monitor.umc.monitor.common.HttpClientUtil.java

/**
 * @Title httpPost//from w ww .ja v  a 2 s .  c  o m
 * @Description TODO(realize the rest interface to access by httpPost)
 * @param url
 * @throws Exception
 * @return int (return StatusCode,If zero error said)
 */
public static int httpPost(String url) throws Exception {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    try {
        CloseableHttpResponse res = httpClient.execute(httpPost);
        try {
            return res.getStatusLine().getStatusCode();
        } finally {
            res.close();
        }
    } catch (ParseException e) {
        LOGGER.error("HttpClient throw ParseException:" + url, e);
    } catch (IOException e) {
        LOGGER.error("HttpClient throw IOException:" + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.error("HttpClient Close throw IOException", e);
        }
    }

    return 0;

}

From source file:org.gbrowser.http.Download.java

public String getPage(String url) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet;/* www .ja  v  a 2s .  c om*/
    CloseableHttpResponse response1 = null;
    StringBuilder buff = new StringBuilder();
    int ch = -1;

    try {
        httpGet = new HttpGet(url.trim());
        response1 = httpclient.execute(httpGet);
        if (response1.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    httpGet.getURI().getPath() + " : " + response1.getStatusLine().getStatusCode() + " : "
                            + response1.getStatusLine().getReasonPhrase());
        }
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        // EntityUtils.consume(entity1);
        InputStream inp = entity1.getContent();
        while ((ch = inp.read()) != -1) {
            buff.append((char) ch);
        }
    } finally {
        if (response1 != null) {
            response1.close();
        }
    }

    return buff.toString();
}

From source file:vn.vndirect.form.model.SendURIModel.java

public SendURIModel(String image, String filenameKH, String filenameKN) {
    try {//from w w  w.ja v  a  2s .  c o m
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(URItoGMC + "?ImgName=" + image + "&csvKH=" + "KH" + filenameKH + ".csv"
                + "&csvKN=" + "KN" + filenameKN + ".csv");
        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=" + "UTF-16");
        //post.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response = httpclient.execute(post);
        System.out.println("Header " + response.getFirstHeader("Location"));
    } catch (Exception e) {
    }

}

From source file:org.winardiaris.uangku.getDataURL.java

String getData(String url) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w w w .  j  a  v a2 s.  co m*/
        HttpGet httpget = new HttpGet(url);
        System.out.println("Executing request " + httpget.getRequestLine());

        ResponseHandler<String> responseHandler;
        responseHandler = new ResponseHandler<String>() {

            @Override
            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 responseURL = httpclient.execute(httpget, responseHandler);
        return responseURL;
    } finally {
        httpclient.close();
    }
}

From source file:com.mycompany.rakornas.getDataURL.java

String getData(String url) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpGet httpget = new HttpGet(url);
        System.out.println("Executing request " + httpget.getRequestLine());

        ResponseHandler<String> responseHandler;
        responseHandler = new ResponseHandler<String>() {

            @Override//ww w . j  ava 2  s .co  m
            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 responseURL = httpclient.execute(httpget, responseHandler);
        return responseURL;
    }
}