Example usage for org.apache.http.impl.client HttpClientBuilder create

List of usage examples for org.apache.http.impl.client HttpClientBuilder create

Introduction

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

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:com.ibm.watson.developer_cloud.professor_languo.it.endpoints.IT_AskAQuestion.java

/**
 * Tests if the ask a question endpoint can be accessed and checks if the return is in JSON
 * format./* w  w w .  j a v a 2  s.c  o m*/
 * 
 * @throws Exception
 */
@Test
public void askAQuestionTest() throws Exception {
    String postUrl = System.getProperty("app.url");
    postUrl = postUrl + "/api/ask_question";

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost postRequest = new HttpPost(postUrl);
    postRequest.addHeader("accept", "application/json");
    postRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");

    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("questionText", "question text"));

    postRequest.setEntity(new UrlEncodedFormEntity(formParams));

    HttpResponse response = httpClient.execute(postRequest);

    String jsonString = EntityUtils.toString(response.getEntity());

    Assert.assertEquals("response was: " + jsonString, 200, response.getStatusLine().getStatusCode());

    try {
        new JSONArray(jsonString);
    } catch (JSONException e) {
        Assert.fail("Response is not in JSON format: " + jsonString + e.getMessage());
    }
}

From source file:stormy.pythian.features.web.support.Clusters.java

private void undeploy(String clusterName, String topologyId) {
    try {/*from   ww w.j  a v  a2  s .c om*/
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpDelete delete = new HttpDelete(
                BASE_API_PATH + "clusters/" + clusterName + "/topologies/" + topologyId);
        httpClient.execute(delete);
    } catch (Exception ex) {
        // Nothing to do
    }
}

From source file:com.dhenton9000.jersey.client.ServerTest.java

@Test
public void testReadingSwaggerDoc() throws Exception {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet mockRequest = new HttpGet(APP_URL);

    HttpResponse mockResponse = client.execute(mockRequest);
    BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent()));
    String theString = IOUtils.toString(rd);
    assertNotNull(theString);/* w w w  .  jav  a2 s.co  m*/
    assertTrue(theString.contains("swagger"));

}

From source file:edu.vt.vbi.patric.cache.ENewsGenerator.java

public boolean createCacheFile(String filePath) {

    boolean isSuccess = false;

    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

        HttpGet httpRequest = new HttpGet(sourceURL);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String strResponseBody = client.execute(httpRequest, responseHandler);

        if (strResponseBody.length() > 0) {
            PrintWriter enewsOut = new PrintWriter(new FileWriter(filePath));
            enewsOut.println(strResponseBody);
            enewsOut.close();/*from  w  w  w .j av  a2  s.com*/
        }
        isSuccess = true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return isSuccess;
}

From source file:br.cefetrj.sagitarii.nunki.comm.WebClient.java

public void doPost(String action, String parameter, String content) throws Exception {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httppost = new HttpPost(gf.getHostURL() + "/" + action);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair(parameter, content));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    httpClient.execute(httppost);// w  w  w  . j  a  v  a 2 s .  co m
    httpClient.close();

}

From source file:ch.ralscha.extdirectspring_itest.ExceptionFormPostControlerTest.java

@Before
public void beforeTest() {
    this.client = HttpClientBuilder.create().build();
    this.post = new HttpPost("http://localhost:9998/controller/router");
}

From source file:ar.edu.ubp.das.src.chat.actions.MessagesListAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        Gson gson = new Gson();

        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String login_tmst = (String) request.getSession().getAttribute("login_tmst");
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("fecha_desde", login_tmst);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }//  www.j a v  a2 s.c o  m

        //parse message data from response
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            request.getSession().setAttribute("ultimo_mensaje",
                    mensajes.get(mensajes.size() - 1).getId_mensaje());
        }

        request.setAttribute("mensajes", mensajes);

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar mostrar mensajes: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("error");
    }
}

From source file:org.wso2.identity.integration.test.entitlement.EntitlementSecurityTestCase.java

@BeforeClass(alwaysRun = true)
public void testInit() throws Exception {
    super.init();
    httpClient = HttpClientBuilder.create().build();
    value = "<script>alert(1);</script>";
    String encodedValue = URLEncoder.encode(value, "UTF-8");
    String temp = backendURL.replaceAll("services/",
            "carbon/policyeditor/prettyPrinter_ajaxprocessor.jsp?xmlString=");
    url = temp + encodedValue;/*from w  ww  . j  a v  a 2 s. co  m*/
}

From source file:professionalpractice3.GETClient.java

static String getBalance(String customerID) throws ClientProtocolException, IOException {
    BufferedReader responseBody = null;
    HttpClient client = HttpClientBuilder.create().build();

    try {/*from ww w  .j av a  2 s  .c  om*/
        //Define a HttpGet request
        HttpGet request = new HttpGet("http://" + localServer);

        //Set Http Headers
        request.addHeader("Accept", "application/xml");
        request.addHeader("Type", "balance");
        request.addHeader("Customer", customerID);

        //Invoke the service
        HttpResponse response = client.execute(request);

        //Verify if the response is valid
        int statusCode = response.getStatusLine().getStatusCode();
        //System.out.println(statusCode);
        if (statusCode != 200) {
            throw new RuntimeException("Failed with HTTP error code .... : " + statusCode);
        } else {
            //If valid, get the response
            responseBody = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = responseBody.readLine();
            return line;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Invalid input");
        return "";
    } finally {
        if (responseBody != null)
            responseBody.close();
    }
}

From source file:javaversoclientexample.VersoClient.java

/**
 * Import Articles Batch method example// www  .  j  ava 2s.  c o m
 */
public void ImportArticlesBatch() {
    // Create the http client
    HttpClient httpClient = HttpClientBuilder.create().build();

    // Here you place the Verso API Url (TestUrl)
    String url = "http://qa-verso-enterprise-service.azurewebsites.net/VersoApiService.svc/ImportArticlesBatch";

    try {

        // Here we create a sample ImportArticles Object to import in Verso
        ImportArticlesBatchInfo batchImport = new ImportArticlesBatchInfo("mnavarro", "123");

        // Your are free to add as many articles as you like
        batchImport.addArticle(new ArticleInfo("TestPart00", "TestPartS00", "Test", "ATE3", "08/06/2015",
                "10/10/2015", "", "", "", ""));

        batchImport.addArticle(new ArticleInfo("TestPart01", "TestPartS01", "Test", "ATE3", "08/06/2015",
                "10/10/2015", "", "", "", "TestBuyChannel"));

        // Create the json body to set the request body
        Gson gson = new Gson();
        String jsonBody = gson.toJson(batchImport);
        StringEntity params = new StringEntity(jsonBody);

        // Prepare http client properties
        HttpPost request = new HttpPost(url);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        // Execute the response        
        HttpResponse response = httpClient.execute(request);

        // Print the request response (Just for testing)
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);

    } catch (Exception ex) {
        // Handle your exception
        System.out.println(ex);

    } finally {
        // Close the  client connection
        httpClient.getConnectionManager().shutdown();
    }
}