Package org.apache.http.client

Examples of org.apache.http.client.HttpClient


    return map;
  }

  public static Map<String, Object> get(String url, Integer connectionTimeout, Integer soTimeout, Map<String, Object> authMap) throws Exception
  {
    HttpClient client = getHttpClient(url, connectionTimeout, soTimeout);
    HttpGet httpclient = new HttpGet(url);
    if (authMap != null)
      httpclient.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials((String) authMap.get("user"), (String) authMap.get("password")), httpclient));
    HttpResponse response = client.execute(httpclient);
    HttpEntity resEntity = response.getEntity();
    String contentCharSet = EntityUtils.getContentCharSet(resEntity);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("status", response.getStatusLine().getStatusCode());
    map.put("response", contentCharSet != null ? new String(EntityUtils.toByteArray(resEntity), contentCharSet) : new String(EntityUtils.toByteArray(resEntity)));
View Full Code Here


  public static Map<String, Object> executeMethod(HttpUriRequest httpUriRequest, String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    HashMap<String, Object> map = new HashMap<String, Object>();
    try
    {
      HttpClient client = getHttpClient(url, connectionTimeout, soTimeout);
      httpUriRequest.setHeader("Accept", "application/json");
      if (url.contains("/Cards/card/search"))
        url = truncData(url);
      long t1 = System.currentTimeMillis();
      HttpResponse response = client.execute(httpUriRequest);
      long t2 = System.currentTimeMillis();
      if (!url.contains("SensitiveController"))
        NewRelic.addCustomParameter(System.currentTimeMillis()+"--"+url, (t2 - t1) + " ms");
      HttpEntity resEntity = response.getEntity();
      String contentCharSet = EntityUtils.getContentCharSet(resEntity);
View Full Code Here

        final int numThreads = Integer.parseInt(args[1]);
        final int numRequests = Integer.parseInt(args[2]);

        System.out.println("Benchmarking against " + url);

        final HttpClient client = createClient();
        PerformanceTest perfTest = new PerformanceTest() {

            @Override
            public void doOperation(int index) {
                HttpResponse response = null;
                try {
                    HttpGet get = new HttpGet(url);
                    response = client.execute(get);
                    response.getEntity().consumeContent();
                } catch(Exception e) {
                    e.printStackTrace();
                } finally {
                    VoldemortIOUtils.closeQuietly(response);
View Full Code Here

        // create REST client for BoxClient
        final ClientConnectionManager[] clientConnectionManager = new ClientConnectionManager[1];
        final IBoxRESTClient restClient = new BoxRESTClient(connectionManager.build()) {
            @Override
            public HttpClient getRawHttpClient() {
                final HttpClient httpClient = super.getRawHttpClient();
                clientConnectionManager[0] = httpClient.getConnectionManager();
                final SchemeRegistry schemeRegistry = clientConnectionManager[0].getSchemeRegistry();
                SSLContextParameters sslContextParameters = configuration.getSslContextParameters();
                if (sslContextParameters == null) {
                    sslContextParameters = new SSLContextParameters();
                }
                try {
                    final SSLSocketFactory socketFactory = new SSLSocketFactory(
                        sslContextParameters.createSSLContext(),
                        SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
                    schemeRegistry.register(new Scheme("https", socketFactory, 443));
                } catch (GeneralSecurityException e) {
                    throw ObjectHelper.wrapRuntimeCamelException(e);
                } catch (IOException e) {
                    throw ObjectHelper.wrapRuntimeCamelException(e);
                }

                // set custom HTTP params
                final Map<String, Object> configParams = configuration.getHttpParams();
                if (configParams != null && !configParams.isEmpty()) {
                    LOG.debug("Setting {} HTTP Params", configParams.size());

                    final HttpParams httpParams = httpClient.getParams();
                    for (Map.Entry<String, Object> param : configParams.entrySet()) {
                        httpParams.setParameter(param.getKey(), param.getValue());
                    }
                }
View Full Code Here

      underlying.set(defaultClient);
    }
  }

  public void restart() {
    HttpClient old = underlying.get();
    if (old != null) {
      // this will kill all of the connections and release the resources for our old client
      old.getConnectionManager().shutdown();
    }
    setup();
  }
View Full Code Here

  public BasicClient(String name, Hosts hosts, StreamingEndpoint endpoint, Authentication auth, boolean enableGZip, HosebirdMessageProcessor processor,
                     ReconnectionManager reconnectionManager, RateTracker rateTracker, ExecutorService executorService,
                     @Nullable BlockingQueue<Event> eventsQueue, HttpParams params, SchemeRegistry schemeRegistry) {
    Preconditions.checkNotNull(auth);
    HttpClient client;
    if (enableGZip) {
      client = new RestartableHttpClient(auth, enableGZip, params, schemeRegistry);
    } else {
      DefaultHttpClient defaultClient = new DefaultHttpClient(new PoolingClientConnectionManager(schemeRegistry), params);
View Full Code Here

        return ok(views.html.community.create.render(user, communityForm, "Create Community", "", ""));
    }

    public static Result create() {
        Logger.info("CREATE");
        HttpClient httpClient = new DefaultHttpClient();
        SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
                .getSchemeRegistry().getScheme("https").getSocketFactory();
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());

        try {
            Logger.info("Creating comm");
            HttpPost request = new HttpPost(Application.baseRestUrl + "/communities");
            request.setHeader("Accept", "application/json");
            request.addHeader("Content-Type", "application/json");
            String token = session("userToken");
            request.addHeader("rest-dspace-token", token);


            Community community = form(Community.class).bindFromRequest().get();

            StringEntity communityEntity = new StringEntity("{\"name\":\""+ community.name +"\"}");

            request.setEntity(communityEntity);
            Logger.info("ready");
            HttpResponse response = httpClient.execute(request);

            Logger.info("response: " + response.toString());
            if(response.getStatusLine().getStatusCode() == 200) {
                Logger.info("ok");
                Community parsedCommunity = Community.parseCommunityFromJSON(Json.parse(EntityUtils.toString(response.getEntity())));
View Full Code Here

            return redirect(routes.Application.status());
        }
    }

    public static Result login() {
        HttpClient httpClient = new DefaultHttpClient();
        SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
                .getSchemeRegistry().getScheme("https").getSocketFactory();
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());

        try {
            HttpPost request = new HttpPost(baseRestUrl + "/login");
            //{"email":"admin@dspace.org","password":"s3cret"}
            //StringEntity params =new StringEntity("{\"email\":\"admin@dspace.org\",\"password\":\"s3cret\"} ");
            DynamicForm requestData = Form.form().bindFromRequest();
            String email = requestData.get("email");
            String password = requestData.get("password");
            StringEntity params =new StringEntity("{\"email\":\"" + email + "\",\"password\":\"" + password + "\"}");
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);

            if(response.getStatusLine().getStatusCode() == 200) {
                String responseBody = EntityUtils.toString(response.getEntity());
                String token = responseBody;
                session().clear();
                session("userToken", token);
            } else {
                session().clear();
            }

            return redirect(controllers.routes.Application.status());
            // handle response here...
        }catch (Exception ex) {
            // handle exception here
            Logger.error(ex.getMessage());
            return internalServerError(ex.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
View Full Code Here

            httpClient.getConnectionManager().shutdown();
        }
    }

    public static Result logout() {
        HttpClient httpClient = new DefaultHttpClient();
        SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
                .getSchemeRegistry().getScheme("https").getSocketFactory();
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());

        try {
            HttpPost request = new HttpPost(baseRestUrl + "/logout");
            request.addHeader("Content-Type", "application/json");
            String token = session("userToken");
            request.addHeader("rest-dspace-token", token);
            HttpResponse response = httpClient.execute(request);

            session().remove("userEmail");
            session().remove("userFullname");
            session().clear();

            if(response.getStatusLine().getStatusCode() == 200) {
                Logger.info("Properly Logged Out");
                return redirect(routes.Application.status());
            } else {
                String responseBody = EntityUtils.toString(response.getEntity());
                Logger.info("Unsuccessful logout");
                return unauthorized("Wrong token to logout with, or already logged out.");
            }

        }catch (Exception ex) {
            // handle exception here
            Logger.error(ex.getMessage());
            return internalServerError(ex.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
View Full Code Here

            httpClient.getConnectionManager().shutdown();
        }
    }

    public static Result status() {
        HttpClient httpClient = new DefaultHttpClient();
        SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
                .getSchemeRegistry().getScheme("https").getSocketFactory();
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());

        try {
            HttpGet request = new HttpGet(baseRestUrl + "/status");
            request.setHeader("Accept", "application/json");
            request.addHeader("content-type", "application/json");
            String token = session("userToken");
            request.addHeader("rest-dspace-token", token);

            HttpResponse response = httpClient.execute(request);
            String responseBody = EntityUtils.toString(response.getEntity());
            User user = new User();
            user = user.parseUserFromJSON(Json.parse(responseBody));
            setSessionFromUser(user);


            return ok(views.html.status.render(user, "Status", responseBody, request.getURI().toString()));

            // handle response here...
        }catch (IOException ex) {
            // handle exception here

            Logger.error(ex.getMessage() + " cause:" + ex.getCause());
            return internalServerError(ex.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.http.client.HttpClient

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.