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.qualinsight.plugins.sonarqube.badges.internal.QualityGateStatusRetriever.java

/**
 * {@link QualityGateStatusRetriever} IoC constructor.
 *
 * @param settings SonarQube {@link Settings}, required to retrieve the "sonar.core.serverBaseURL" property.
 * @throws URISyntaxException if "sonar.core.serverBaseURL" in SonarQube settings is a malformed URI.
 *//*from  w  w w.  j a  v a 2 s . c  o m*/
public QualityGateStatusRetriever(final Settings settings) throws URISyntaxException {
    this.settings = settings;
    this.httpclient = HttpClients.createDefault();
    this.httpGet = new HttpGet();
    this.responseHandler = new QualityGateServiceResponseHandler();
    if (this.settings.getString(SERVER_BASE_URL_KEY)
            .equals(this.settings.getDefaultValue(SERVER_BASE_URL_KEY))) {
        LOGGER.warn(
                "'{}' property has default value which may lead to unexpected behavior. Make sure that you've correctly configured this property in SonarQube's general settings.",
                SERVER_BASE_URL_KEY);
    }
    LOGGER.info("QualityGateStatusRetriever is now ready.");
}

From source file:net.xenqtt.httpgateway.HttpGatewayHandler.java

/**
 * The handler sets the response status, content-type, and marks the request as handled before it generates the body of the response using a writer. There
 * are a number of built in <a href="http://download.eclipse.org/jetty/stable-9/xref/org/eclipse/jetty/server/handler/package-summary.html">handlers</a>
 * that might come in handy./*from www .  j  av a2 s.c  o  m*/
 * 
 * @param target
 *            the target of the request, which is either a URI or a name from a named dispatcher.
 * @param baseRequest
 *            the Jetty mutable request object, which is always unwrapped.
 * @param request
 *            the immutable request object, which may have been wrapped by a filter or servlet.
 * @param response
 *            the response, which may have been wrapped by a filter or servlet.
 * 
 * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // FIXME [jim] - make sure http 1.1 persistent connections are being used on both server and client sides

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://www.google.com" + target);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {
        response.setStatus(response1.getStatusLine().getStatusCode());
        HttpEntity entity = response1.getEntity();
        InputStream in = entity.getContent();
        OutputStream out = response.getOutputStream();
        for (int i = in.read(); i >= 0; i = in.read()) {
            out.write(i);
        }
    } finally {
        response1.close();
    }

    baseRequest.setHandled(true);

    // TODO Auto-generated method stub
}

From source file:org.wuspba.ctams.ui.server.ServerUtils.java

public static String post(URI uri, String xml) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    String ret;/* w  ww  . j  a v a2 s  .c o  m*/

    httpPost.setEntity(xmlEntity);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        HttpEntity entity = response.getEntity();

        ret = convertEntity(entity);

        EntityUtils.consume(entity);
    }

    return ret;
}

From source file:cpcc.com.services.CommunicationServiceImpl.java

/**
 * {@inheritDoc}/*w  w  w  .  j a va2s .  c o  m*/
 */
@Override
public CommunicationResponse transfer(RealVehicle realVehicle, String connector, byte[] data)
        throws ClientProtocolException, IOException {
    HttpPost request = new HttpPost(realVehicle.getUrl() + connectorMap.get(connector));

    HttpEntity entity = EntityBuilder.create().setBinary(data).build();
    request.setEntity(entity);

    try (CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(request)) {
        HttpEntity responseEntity = response.getEntity();
        InputStream ins = responseEntity.getContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(ins, baos);
        byte[] content = baos.toByteArray();

        boolean ok = response.getStatusLine().getStatusCode() == 200;

        CommunicationResponse r = new CommunicationResponse();
        r.setStatus(ok ? Status.OK : Status.NOT_OK);
        r.setContent(content);
        return r;
    }
}

From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java

/**
 * set user and password for basic authentication
 *//*from www  .ja v a 2s .  c  o  m*/
public String postContentToUrl(String url, String content) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "application/xml");
    HttpEntity entity = null;

    HttpClientContext context = initAuthIfNeeded(url);

    try {
        entity = new StringEntity(content);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }

    post.setEntity(entity);
    HttpResponse response;
    try {
        response = httpclient.execute(post, context);
        if (response.getStatusLine().getStatusCode() != 200) {
            log.error("response code not ok: " + response.getStatusLine().getStatusCode());
        }
        entity = response.getEntity();
        return EntityUtils.toString(entity);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return "";
}

From source file:org.jboss.as.test.integration.web.session.SessionInvalidateTestCase.java

@Test
public void testInvalidateSessions() throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {

        ModelNode operation = new ModelNode();
        operation.get(ModelDescriptionConstants.OP).set("invalidate-session");
        operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress
                .parseCLIStyleAddress("/deployment=invalidate.war/subsystem=undertow").toModelNode());
        operation.get("session-id").set("fake");
        ModelNode opRes = managementClient.getControllerClient().execute(operation);
        Assert.assertEquals("success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
        Assert.assertEquals(false, opRes.get(ModelDescriptionConstants.RESULT).asBoolean());
        HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress()
                + ":8080/invalidate/SessionPersistenceServlet");
        HttpResponse res = client.execute(get);
        String sessionId = null;/*w w w  .j av  a2s  .com*/
        for (Header cookie : res.getHeaders("Set-Cookie")) {
            if (cookie.getValue().startsWith("JSESSIONID=")) {
                sessionId = cookie.getValue().split("=")[1].split("\\.")[0];
                break;
            }
        }
        Assert.assertNotNull(sessionId);
        String result = EntityUtils.toString(res.getEntity());
        assertEquals("0", result);
        result = runGet(get, client);
        assertEquals("1", result);
        result = runGet(get, client);
        assertEquals("2", result);

        operation.get("session-id").set(sessionId);
        opRes = managementClient.getControllerClient().execute(operation);
        Assert.assertEquals("success", opRes.get(ModelDescriptionConstants.OUTCOME).asString());
        Assert.assertEquals(true, opRes.get(ModelDescriptionConstants.RESULT).asBoolean());

        result = runGet(get, client);
        assertEquals("0", result);
        result = runGet(get, client);
        assertEquals("1", result);
    }
}

From source file:ejb.services.MarvelService.java

@GET
@Path("/listaPopup/{login}")
@Produces({ "application/text" })
public String listaPopup(@PathParam("login") final String login) {
    List<Usuario> usuarios = new ArrayList<Usuario>();
    usuarios = usuarioBean.listLogin(login);
    Usuario u = usuarios.get(0);//from  www.j ava  2 s .  c om

    String apikey = "62cc7f7bd41e3346a1af737e0449428b";
    String privatekey = "a9e5cccf7acc7f9ce2555471b5b6fc51d5725df6";
    String urlbase = "http://gateway.marvel.com/v1/public/characters";
    //Criao de um timestamp
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhhmmss");
    String ts = sdf.format(date);

    //Criao do HASH
    String hashStr = hash.MD5(ts + privatekey + apikey);
    String uri;
    String nomeAvatar = u.getAvatar();
    //Converso necessria para aplicar o %20 no nome

    //String[] name = nomeAvatar.split(" ");
    //String nomeOk = name[0] + "%20" + name[1];
    nomeAvatar.replace(" ", "%20");
    //url de consulta
    uri = urlbase + "?nameStartsWith=" + nomeAvatar + "&ts=" + ts + "&apikey=" + apikey + "&hash=" + hashStr;
    //System.out.println(uri);
    try {
        HttpClient cliente = HttpClients.createDefault();

        //HttpHost proxy = new HttpHost("172.16.0.10", 3128, "http");
        //RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet(uri);
        // httpget.setConfig(config);
        HttpResponse response = cliente.execute(httpget);
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        Header[] h = response.getAllHeaders();

        for (Header head : h) {
            System.out.println(head.getValue());
        }

        HttpEntity entity = response.getEntity();

        StringReader readerLine = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder out = new StringBuilder();
            String line;

            line = reader.readLine();
            readerLine = new StringReader(line);

            reader.close();
            instream.close();

            JSONObject jsonObject = (JSONObject) new JSONParser().parse(line);
            JSONObject jsonObjectData = (JSONObject) jsonObject.get("data");
            JSONArray lang = (JSONArray) jsonObjectData.get("results");
            JSONObject jsonObjectDados = (JSONObject) lang.get(0);

            JSONObject jsonPath = (JSONObject) jsonObjectDados.get("thumbnail");

            String nomeMarvel = (String) jsonObjectDados.get("name");
            String descricao = (String) jsonObjectDados.get("description");
            String urlImg = (String) jsonPath.get("path");

            String result = "<p>Personagem: " + nomeMarvel + "</p> <br />";
            result += "<p>Descrio: " + descricao + "</p> <br />";
            result += "<img src='" + urlImg + ".jpg' alt='foto'/ height='200' width='200'>";
            return result;

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void notAuthenticated() throws IOException {
    final CloseableHttpClient client = HttpClients.createDefault();

    final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello");
    final CloseableHttpResponse resp = client.execute(httpGet);
    try {/*from   w  w w  .j a v  a 2  s.c  o m*/
        // Without login, it fails with a 403, not authorized
        assertEquals(403, resp.getStatusLine().getStatusCode());

    } finally {
        resp.close();
    }
}

From source file:network.thunder.client.communications.HTTPS.java

public boolean connectPOST(String URL) {
    try {/*w w  w  .  j a v a2 s . c  om*/

        RequestConfig.custom().setConnectTimeout(10 * 1000).build();
        httpClient = HttpClients.createDefault();
        httpPost = new HttpPost(URL);
        nvps = new ArrayList<NameValuePair>();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:net.duckling.probe.ui.cron.AccessURLJob.java

@SuppressWarnings("finally")
public WatchedUrl HttpTest() throws ClientProtocolException, IOException {
    WatchedUrl watchedUrl = new WatchedUrl();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    long start = System.currentTimeMillis();
    try {//from  w w w . j  a v a  2 s . c om
        switch (method) {
        case "GET":
            HttpGet httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            break;
        case "POST":
            HttpPost httppost = new HttpPost(url);
            response = httpclient.execute(httppost);
            break;
        case "HEAD":
            HttpHead httphead = new HttpHead(url);
            response = httpclient.execute(httphead);
            break;
        }
    } finally {
        int responseTime = (int) (System.currentTimeMillis() - start);
        if (response != null) {
            watchedUrl.setStatusCode(response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200
                    || response.getStatusLine().getStatusCode() == 302) {
                watchedUrl.setAvailability(true);
                alertServiceImpl.conutSuccess(collector);
            } else {
                watchedUrl.setAvailability(false);
                alertServiceImpl.countFail(collector);
            }

        } else {
            watchedUrl.setAvailability(false);
            alertServiceImpl.countFail(collector);
        }
        watchedUrl.setResponseTime(responseTime);
        watchedUrl.setCollectorId(collector.getId());
        watchedUrl.setProductId(collector.getProductId());
        watchedUrl.setMethod(method);
        watchedUrl.setWatchTime(new Date());
        httpclient.close();
        return watchedUrl;
    }

}