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:org.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }/*from   ww  w .  ja  v a 2 s .  c o m*/
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:edu.se.ustc.ClientWithResponseHandler.java

public List<BusRouteInfo> run(String URL) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<BusRouteInfo> bsrList = new ArrayList<BusRouteInfo>();
    try {/*from ww  w .j a  v a2s.  c  om*/
        HttpGet httpget = new HttpGet(URL);
        //debug
        //System.out.println("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);
        //System.out.println("----------------------------------------");

        //System.out.println(responseBody);

        String str = responseBody.substring(responseBody.indexOf("table"), responseBody.lastIndexOf("table"));
        //debug
        //System.out.println(str);

        BusRouteInfo binfo = new BusRouteInfo();
        bsrList = binfo.getBusRouteInfoList(str);

        //debug, print all infomation
        //binfo.printBusRouteInfo(bsrList);

        //select the db
        //dbUtil db = new dbUtil();
        //result=db.executeQuery("SELECT * FROM station_stats");
        //         if(result!=null)
        //             System.out.println(result.getString(1));
    } finally {
        httpclient.close();
    }

    return bsrList;
}

From source file:org.apache.sling.launchpad.LaunchpadReadyRule.java

@Override
protected void before() throws Throwable {

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        for (Check check : checks) {
            runCheck(client, check);//from w ww.j a v a  2s . co m
        }
    }
}

From source file:project.latex.balloon.writer.HttpDataWriter.java

void sendPostRequest(String rawString) throws IOException {
    String jsonString = getJsonStringFromRawData(rawString);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringEntity entity = new StringEntity(jsonString, ContentType.create("plain/text", Consts.UTF_8));
    HttpPost httppost = new HttpPost(receiverUrl);
    httppost.addHeader("content-type", "application/json");
    httppost.setEntity(entity);//from   ww w  . j a v a 2 s  .co m

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

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
            StringBuilder stringBuilder = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                stringBuilder.append(line);
                line = reader.readLine();
            }
            return stringBuilder.toString();
        }
    };

    String responseString = httpclient.execute(httppost, responseHandler);
    logger.info(responseString);
}

From source file:com.networknt.metrics.MetricsHandlerTest.java

@Test
public void testMetrics() throws Exception {
    String url = "http://localhost:8080/v2/pet/111";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader("Authorization",
            "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTc5MDAzNTcwOSwianRpIjoiSTJnSmdBSHN6NzJEV2JWdUFMdUU2QSIsImlhdCI6MTQ3NDY3NTcwOSwibmJmIjoxNDc0Njc1NTg5LCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJ3cml0ZTpwZXRzIiwicmVhZDpwZXRzIl19.mue6eh70kGS3Nt2BCYz7ViqwO7lh_4JSFwcHYdJMY6VfgKTHhsIGKq2uEDt3zwT56JFAePwAxENMGUTGvgceVneQzyfQsJeVGbqw55E9IfM_uSM-YcHwTfR7eSLExN4pbqzVDI353sSOvXxA98ZtJlUZKgXNE1Ngun3XFORCRIB_eH8B0FY_nT_D1Dq2WJrR-re-fbR6_va95vwoUdCofLRa4IpDfXXx19ZlAtfiVO44nw6CS8O87eGfAm7rCMZIzkWlCOFWjNHnCeRsh7CVdEH34LF-B48beiG5lM7h4N12-EME8_VDefgMjZ8eqs1ICvJMxdIut58oYbdnkwTjkA");
    try {/* ww  w  . j a v  a  2s. c o m*/
        CloseableHttpResponse response = client.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200, statusCode);
        if (statusCode == 200) {
            String s = IOUtils.toString(response.getEntity().getContent(), "utf8");
            Assert.assertNotNull(s);
            Assert.assertEquals("test", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);//  w  w  w  . j a va  2  s  . c  o  m
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:ac.simons.tests.oembed.ExampleTest.java

@Test
public void youtubeJson() throws OembedException {
    final Oembed oembed = new OembedBuilder(HttpClients.createDefault())
            .withProviders(new OembedProviderBuilder().withName("youtube").withFormat("json").withMaxWidth(480)
                    .withEndpoint("http://www.youtube.com/oembed")
                    .withUrlSchemes("http://(www|de)\\.youtube\\.com/watch\\?v=.*").build())
            .build();//from  www .  j av  a  2s  .  c  o  m
    OembedResponse response = oembed.transformUrl("http://www.youtube.com/watch?v=lh_em3-ndVw");
    System.out.println(response);
}

From source file:ddf.registry.client.rest.internal.RestRegistryClient.java

/**
 * Set the external registry that should be queried.
 * @param url URL to the external registry
 *//*from w w w.j av a 2 s. co  m*/
public void setRegistryUrl(String url) {
    if (StringUtils.isNotBlank(url)) {
        if (!configurationList.isEmpty()) {
            LOGGER.debug("Updating registry URL and removing old sources.");
            clearConfigurations();
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String endpoints = IOUtils.toString(response.getEntity().getContent());
            JSONArray endpointArray = new JSONArray(endpoints);
            for (int i = 0; i < endpointArray.length(); i++) {
                JSONObject curEndpoint = endpointArray.getJSONObject(i);

                // get endpoint props
                String type = curEndpoint.getString(ServiceInfo.TYPE_KEY);
                String endpointUrl = curEndpoint.getString(ServiceInfo.URL_KEY);

                // get factory pid using service type
                String pid = serviceResolver.getFactoryPid(type);
                LOGGER.debug("Got factory pid of [{}] for service of type [{}].", pid, type);

                // create new source pointing to this endpoint
                Configuration siteConfig = configAdmin.createFactoryConfiguration(pid, null);
                Dictionary<String, Object> properties = new Hashtable<>();
                properties.put("endpointUrl", endpointUrl);
                properties.put("id", pid);
                LOGGER.debug("Creating new source that points to {}.", endpointUrl);
                siteConfig.update(properties);
                configurationList.add(siteConfig);
            }
        } catch (Exception e) {
            LOGGER.warn("Encountered an error while trying to connect to the remote registry.", e);
        } finally {
            IOUtils.closeQuietly(httpClient);
        }
    } else {
        LOGGER.debug(
                "Registry location reset due to url being empty or null. Deleting any remote sources created from previous registry.");
        clearConfigurations();
    }
}