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.dhenton9000.jersey.client.ServerTest.java

@Test
public void testRESTCallForRestaurant() throws Exception {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet mockRequest = new HttpGet(APP_URL + "/webapi/restaurant/4");

    HttpResponse mockResponse = client.execute(mockRequest);
    BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent()));
    String theString = IOUtils.toString(rd);
    //LOG.debug(theString);
    assertTrue(theString.contains("Arby"));
}

From source file:demo.web.doAGoodActionServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  ww  . j  a  v  a  2 s  . co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet dokkkkAGoodActionServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet doAGoodAdssfsdfctionServlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");

        JSONObject json = new JSONObject();
        json.put("description", "Une_app_de_test");
        json.put("name", "MyTest");
        json.put("password", "password");

        HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 
        HttpPost requestHttpPost;

        String addresse = "http://localhost:8090/api";

        requestHttpPost = new HttpPost(addresse + "/applications");
        StringEntity params = new StringEntity(json.toString());
        requestHttpPost.addHeader("content-type", "application/json");
        requestHttpPost.setEntity(params);
        HttpResponse responseHttpResponse = httpClient.execute(requestHttpPost);

        request.getRequestDispatcher("WEB-INF/pages/login.jsp").forward(request, response);
    }
}

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

@Test
public void testApi() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {/*www  .  j av a 2 s.  c o  m*/
        HttpGet g = new HttpGet("http://localhost:9998/controller/api.js?group=itest_info");
        response = client.execute(g);
        String responseString = EntityUtils.toString(response.getEntity());
        String contentType = response.getFirstHeader("Content-Type").getValue();
        ApiControllerTest.compare(responseString, contentType, api(), ApiRequestParams.builder().build());
        SimpleServiceTest.assertCacheHeaders(response, false);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:demo.web.goodKarma.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww  .  ja v  a2 s .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet goodKarma</title>");
        out.println("</head>");
        out.println("<body>");

        out.println("</body>");
        out.println("</html>");
        String addresse = "http://localhost:8090/api";

        JSONObject jsonLogin = new JSONObject();
        jsonLogin.put("name", "MyTest");
        jsonLogin.put("password", "password");

        HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 
        HttpPost requestHttpPostLogin;

        requestHttpPostLogin = new HttpPost(addresse + "/login");
        StringEntity paramsLogin = new StringEntity(jsonLogin.toString());

        requestHttpPostLogin.addHeader("content-type", "application/json");

        requestHttpPostLogin.setEntity(paramsLogin);
        HttpResponse responseHttpResponse = httpClient.execute(requestHttpPostLogin);

        HttpEntity entity = responseHttpResponse.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");

        out.print(responseString);

        JSONObject obj = new JSONObject(responseString);
        out.println("mytoken" + obj.getString("token")); //John

        JSONObject jsonPS = new JSONObject();
        jsonPS.put("name", "karma");

        HttpClient httpClientPS = HttpClientBuilder.create().build(); //Use this instead 
        HttpPost requestHttpPostPS;

        requestHttpPostPS = new HttpPost(addresse + "/pointScales");
        StringEntity paramsPS = new StringEntity(jsonPS.toString());
        requestHttpPostPS.addHeader("content-type", "application/json");
        requestHttpPostPS.addHeader("token", obj.getString("token"));

        requestHttpPostPS.setEntity(paramsPS);
        HttpResponse responseHttpResponsePS = httpClientPS.execute(requestHttpPostPS);

    }
}

From source file:org.apache.unomi.itests.BasicIT.java

@Test
public void testContextJS() throws IOException {
    HttpUriRequest request = new HttpGet(URL + "/context.js?sessionId=aa3b04bd-8f4d-4a07-8e96-d33ffa04d3d9");
    CloseableHttpResponse response = HttpClientBuilder.create().build().execute(request);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the profile MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    String responseContent = null;
    try {/* w w w  . ja  v a 2  s  . c  om*/
        System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        responseContent = EntityUtils.toString(entity);
    } finally {
        response.close();
    }
    Assert.assertTrue("Response should contain context object",
            responseContent.contains("window.digitalData = window.digitalData || {};"));
    // @todo we should check the validity of the context object, but this is rather complex since it would
    // potentially require parsing the Javascript !
}

From source file:access.test.PiazzaEnvironmentTests.java

/**
 * Test initialization//w w  w .  j  av  a 2  s  .c om
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    this.httpClient = HttpClientBuilder.create().build();
    ReflectionTestUtils.setField(this.piazzaEnvironment, "httpClient", this.httpClient);
    ReflectionTestUtils.setField(this.piazzaEnvironment, "restTemplateConnectionReadTimeout", 2000);

    ReflectionTestUtils.setField(this.piazzaEnvironment, "postgresServiceKeyUser", "junit_user");
    ReflectionTestUtils.setField(this.piazzaEnvironment, "postgresServiceKeyPassword", "junit_user_password");
    ReflectionTestUtils.setField(this.piazzaEnvironment, "postgresPort", "5432");
    ReflectionTestUtils.setField(this.piazzaEnvironment, "postgresDatabase", "junit_database_name");
    ReflectionTestUtils.setField(this.piazzaEnvironment, "postgresHost", "junit_host");

    Mockito.when(this.accessUtilities.getGeoServerBaseUrl()).thenReturn("http://localhost:8080/geoserver");
}

From source file:cfappserver.Bot.java

public static String genData(String user, String pass, int semnum) {
    try {/*from   w ww  .java2s  . co m*/
        String url = "https://home-access.cfisd.net/HomeAccess/Account/LogOn?ReturnUrl=%2fhomeaccess%2f";
        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
        HttpClient client = new DefaultHttpClient(httpParams);
        CookieStore httpCookieStore = new BasicCookieStore();
        HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
        HttpPost post = new HttpPost(url);
        Scanner kk = new Scanner(System.in);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("Database", "10"));
        urlParameters.add(new BasicNameValuePair("LogOnDetails.UserName", user));
        urlParameters.add(new BasicNameValuePair("LogOnDetails.Password", pass));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
        }

        response = client.execute(new HttpGet("https://home-access.cfisd.net/HomeAccess/Classes/Classwork"));
        rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        result = new StringBuffer();
        line = "";
        ClssPkg classpack = null;
        while ((line = rd.readLine()) != null) {
            if (line.contains("<li class=\"sg-banner-menu-element sg-menu-element-identity\">")) {
                classpack = new ClssPkg(rd.readLine().split("<|>")[2],semnum);
            }
        }
        if (classpack == null) {
            return "Wrong login";
        }
        getReport(client, classpack);
        getLunch(client, classpack);
        getAssignments(client, classpack);
        getAbsences(client, classpack, urlParameters);
        return classpack.toString();
    } catch (Exception ex) {
        Logger.getLogger(Bot.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Wrong login";
}

From source file:io.liveoak.container.BasicServerTest.java

@Before
public void setUpClient() throws Exception {
    this.httpClient = HttpClientBuilder.create().build();
}

From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java

@Override
public CloseableHttpClient createHttpClient(HttpHost httpHost, boolean acceptAnyCertificate) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    //configure proxy from system environment
    builder.setRoutePlanner(new SystemDefaultRoutePlanner(null));

    //accept any certificate if necessary
    if ("https".equals(httpHost.getSchemeName()) && acceptAnyCertificate) {
        SSLConnectionSocketFactory icsf = getInsecureSSLSocketFactory();
        builder.setSSLSocketFactory(icsf);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", icsf).build();
        HttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(cm);
    }/*from  ww  w . j  av a2  s . c  o  m*/

    //add an interceptor that replaces the invalid Content-Type
    //'none' by 'identity'
    builder.addInterceptorFirst(new ContentEncodingNoneInterceptor());

    CloseableHttpClient client = builder.build();
    return client;
}

From source file:com.github.aistomin.http.PostRequest.java

@Override
public String execute() throws Exception {
    final Request request = Request.Post(this.resource);
    for (final Map.Entry<String, String> item : this.heads.entrySet()) {
        request.addHeader(item.getKey(), item.getValue());
    }//  ww  w .  j av a2  s. c o  m
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new LaxRedirectStrategy());
    builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
        public boolean retryRequest(final HttpResponse response, final int count, final HttpContext context) {
            return count <= PostRequest.RETRY_COUNT;
        }

        public long getRetryInterval() {
            return PostRequest.RETRY_INTERVAL;
        }
    });
    return Executor.newInstance(builder.build()).execute(request).returnContent().asString();
}