Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

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

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java

/** */
@SuppressWarnings("deprecation")
private List<TyckTillProjectData> getAllProjects(String token) {
    if (token == null) {
        throw new RuntimeException("Token cannot be null. Please set it first.");
    }// ww  w.jav  a  2 s .co m

    DefaultHttpClient client = getNewClient();
    List result = null;
    try {
        HttpResponse response = HTTPUtils.makeRequest(GET_PROJECT, token, client);
        HttpEntity entity = response.getEntity();
        entity.writeTo(System.out);

        // Convert the xml response into an object
        result = getProjectData((entity.getContent()));

    } catch (Exception e) {
        throw new RuntimeException("TODO: Handle this exception better", e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return result;
}

From source file:eu.juniper.MonitoringLib.java

/**
 * REST query to a resource by the given URL
 * (not a public function)//w  w w . j  ava2 s . c  om
 *
 * @param URL URL of the resource which is requested
 * @return Response of the REST GET call as String
 * @throws ParseException
 */
private String getResponse(String URL) throws ParseException {
    String responseString = "";

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(URL);

        System.out.println("executing GET request:\n" + httpGet.getRequestLine());

        HttpResponse response;
        response = httpclient.execute(httpGet);
        HttpEntity responseEntity = response.getEntity();

        responseString = EntityUtils.toString(responseEntity);

        httpclient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return responseString;
}

From source file:com.wenzani.maven.mongodb.InitMongoDb.java

private void download() {
    getLog().info(String.format("Downloading MongoDB from %s", mongoDbUrl));
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from www. j a va2  s. c  o  m*/
        URI uri = new URI(mongoDbUrl);
        HttpGet httpget = new HttpGet(uri);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String fileName = getTarGzFileName();
        FileUtils.copyInputStreamToFile(entity.getContent(), new File(fileName));
    } catch (ClientProtocolException e) {
        getLog().error(ExceptionUtils.getFullStackTrace(e));
    } catch (IOException e) {
        getLog().error(ExceptionUtils.getFullStackTrace(e));
    } catch (URISyntaxException e) {
        getLog().error(ExceptionUtils.getFullStackTrace(e));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.uoyabause.android.AsyncDownload.java

private Integer sendReport(String uri, String product_id) {

    Log.d("sendReport", "================ sendReport start ================");

    mainActivity._report_status = Yabause.REPORT_STATE_FAIL_CONNECTION;

    DefaultHttpClient client = new DefaultHttpClient();
    try {/*  w ww  .j ava2s  . c o m*/
        Credentials credentials = new UsernamePasswordCredentials(mainActivity.getString(R.string.basic_user),
                mainActivity.getString(R.string.basic_password));
        AuthScope scope = new AuthScope(null, -1);
        client.getCredentialsProvider().setCredentials(scope, credentials);
    } catch (Exception e) {
        Log.d("sendReport", "error " + e.getMessage());
        e.printStackTrace();
        client.getConnectionManager().shutdown();
        return 0;
    }

    String device_id = Settings.Secure.getString(mainActivity.getContentResolver(), Settings.Secure.ANDROID_ID);
    try {
        long id = -1;
        Log.d("sendReport", "uri=" + uri + "games/" + product_id);
        HttpGet httpGet = new HttpGet(new URI(uri + "games/" + product_id));
        HttpResponse resp = client.execute(httpGet);
        int status = resp.getStatusLine().getStatusCode();
        Log.d("sendReport", "get status=" + status);
        if (HttpStatus.SC_OK == status) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resp.getEntity().writeTo(outputStream);
                String data;
                data = outputStream.toString(); // JSON
                JSONObject rootObject = new JSONObject(data);
                Log.d("sendReport", "get id respose=" + data);
                if (rootObject.getBoolean("result") == true) {
                    id = rootObject.getLong("id");
                }
            } catch (Exception e) {
                Log.d("sendReport", "error");
                e.printStackTrace();
            }
        } else {
        }
        if (id == -1) {

            HttpPost httpPost = new HttpPost(new URI(uri + "games/"));
            StringEntity se = new StringEntity(mainActivity.current_game_info.toString());
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            resp = client.execute(httpPost);
            status = resp.getStatusLine().getStatusCode();
            Log.d("sendReport", "post stats=" + status);
            if (HttpStatus.SC_CREATED == status || HttpStatus.SC_OK == status) {
                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    resp.getEntity().writeTo(outputStream);
                    String data;
                    data = outputStream.toString(); // JSON
                    Log.d("sendReport", "post respose=" + data);
                    JSONObject rootObject = new JSONObject(data);
                    if (rootObject.getBoolean("result") == true) {
                        id = rootObject.getLong("id");
                    }
                } catch (Exception e) {
                    Log.d("sendReport", "error");
                    e.printStackTrace();
                }
            } else {
            }

        }
        Log.d("sendReport", "ID=" + id);
        if (id == -1) {
            client.getConnectionManager().shutdown();
            return -1;
        }

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mainActivity);
        String cputype = sharedPref.getString("pref_cpu", "2");
        String gputype = sharedPref.getString("pref_video", "1");
        JSONObject reportJson = new JSONObject();
        reportJson.put("rating", mainActivity.current_report._rating);
        if (mainActivity.current_report._message != null) {
            reportJson.put("message", mainActivity.current_report._message);
        }
        reportJson.put("emulator_version", Home.getVersionName(mainActivity));
        reportJson.put("device", android.os.Build.MODEL);
        reportJson.put("user_id", 1);
        reportJson.put("device_id", device_id);
        reportJson.put("game_id", id);
        reportJson.put("cpu_type", cputype);
        reportJson.put("video_type", gputype);
        JSONObject sendJson = new JSONObject();
        sendJson.put("report", reportJson);
        if (mainActivity.current_report._screenshot) {
            JSONObject jsonObjimg = new JSONObject();
            jsonObjimg.put("data", mainActivity.current_report._screenshot_base64);
            jsonObjimg.put("filename", mainActivity.current_report._screenshot_save_path);
            jsonObjimg.put("content_type", "image/png");
            JSONObject jsonObjgame = sendJson.getJSONObject("report");
            jsonObjgame.put("screenshot", jsonObjimg);
            File file = new File(mainActivity.current_report._screenshot_save_path);
            file.delete();
        }
        Log.d("sendReport", reportJson.toString());
        HttpPost httpPost = new HttpPost(new URI(uri + "reports/"));
        StringEntity se = new StringEntity(sendJson.toString());
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        resp = client.execute(httpPost);
        status = resp.getStatusLine().getStatusCode();
        if (HttpStatus.SC_CREATED == status || HttpStatus.SC_OK == status) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resp.getEntity().writeTo(outputStream);
                String data;
                data = outputStream.toString(); // JSON
                JSONObject rootObject = new JSONObject(data);
                Log.d("sendReport", "get respose=" + data);
                if (rootObject.getBoolean("result") == true) {
                    mainActivity._report_status = Yabause.REPORT_STATE_SUCCESS;
                } else {
                    int return_code = rootObject.getInt("code");
                    mainActivity._report_status = return_code;
                }
            } catch (Exception e) {
                Log.d("sendReport", "error");
                e.printStackTrace();
            }
            client.getConnectionManager().shutdown();
            return 0;
        }
        client.getConnectionManager().shutdown();
        return -1;

    } catch (Exception e) {
        Log.d("sendReport", "error:" + e.getMessage());
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    return -1;
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Returns the preconfigured http client,
 * using CertificateVerificationService, timeouts, user-agent,
 * hostname verifier, proxy settings are used from global java settings,
 * if protected site is hit asks for credentials
 * using util.swing.AuthenticationWindow.
 * @param usernamePropertyName the property to use to retrieve/store
 * username value if protected site is hit, for username
 * ConfigurationService service is used.
 * @param passwordPropertyName the property to use to retrieve/store
 * password value if protected site is hit, for password
 * CredentialsStorageService service is used.
 * @param credentialsProvider if not null provider will bre reused
 * in the new client/*  w  ww. j  a v a 2 s  . c  o m*/
 * @param address the address we will be connecting to
 */
public static DefaultHttpClient getHttpClient(String usernamePropertyName, String passwordPropertyName,
        final String address, CredentialsProvider credentialsProvider) throws IOException {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    HttpProtocolParams.setUserAgent(httpClient.getParams(),
            System.getProperty("sip-communicator.application.name") + "/"
                    + System.getProperty("sip-communicator.version"));

    SSLContext sslCtx;
    try {
        sslCtx = HttpUtilActivator.getCertificateVerificationService()
                .getSSLContext(HttpUtilActivator.getCertificateVerificationService().getTrustManager(address));
    } catch (GeneralSecurityException e) {
        throw new IOException(e.getMessage());
    }

    // note to any reviewer concerned about ALLOW_ALL_HOSTNAME_VERIFIER:
    // the SSL context obtained from the certificate service takes care of
    // certificate validation
    try {
        Scheme sch = new Scheme("https", 443, new SSLSocketFactoryEx(sslCtx));
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Throwable t) {
        logger.error("Error creating ssl socket factory", t);
    }

    // set proxy from default jre settings
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (credentialsProvider == null)
        credentialsProvider = new HTTPCredentialsProvider(usernamePropertyName, passwordPropertyName);
    httpClient.setCredentialsProvider(credentialsProvider);

    // enable retry connecting with default retry handler
    // when connecting has prompted for authentication
    // connection can be disconnected nefore user answers and
    // we need to retry connection, using the credentials provided
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    return httpClient;
}

From source file:Recieve.java

public String send(String URL) {
    String output2 = "";
    try {//from   w  w  w . j av a  2s  . co m

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(URL);
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            output2 = output;
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();

        return output2;
    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return output2;
}

From source file:org.jboss.as.test.integration.web.annotationsmodule.WebModuleDeploymentTestCase.java

@Test
public void testSimpleBeanInjected() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//  ww  w  . j  a  va2 s  .c  om
        HttpGet httpget = new HttpGet(url.toExternalForm() + "/servlet");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        assertEquals(200, statusLine.getStatusCode());

        String result = EntityUtils.toString(entity);
        Assert.assertEquals(ModuleServlet.MODULE_SERVLET, result);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:hu.balazsbakai.sq.util.RestUtil.java

private void executeRequest(HttpUriRequest request, String url) {

    DefaultHttpClient client = getNewTrustedHttpClient();// new DefaultHttpClient();

    HttpResponse httpResponse;/*from ww  w .j  av  a 2s.c o  m*/

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity httpEntity = httpResponse.getEntity();

        if (httpEntity != null) {
            InputStream inputStream = httpEntity.getContent();
            response = convertStreamToString(inputStream);
            inputStream.close();// Closing the input stream will trigger connection release
        }

    } catch (Exception e) {
        LogUtil.e("executeRequest", e);
        client.getConnectionManager().shutdown();
    }

}

From source file:org.xmlsh.internal.commands.http.java

private void disableTrust(DefaultHttpClient client, String disableTrustProto)
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() {

        @Override/*from  www.j  a  v  a 2  s  . co m*/
        public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub
            return false;
        }

    }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    int port = client.getConnectionManager().getSchemeRegistry().getScheme(disableTrustProto).getDefaultPort();

    client.getConnectionManager().getSchemeRegistry()
            .register(new Scheme(disableTrustProto, port, socketFactory));
}

From source file:capabilities.DevicesSO.java

@Override
public String dbSearch(String userAgent) throws Exception {
    String urlInicio, urlCapacidades, urlFim, urlPath;
    String capacidades = "device_os%0D%0A" // Sistema Operacional
            + "device_os_version%0D%0A" // Verso do sistema operacional
            + "model_name%0D%0A" // Modelo do dispositivo
            + "brand_name%0D%0A" // Marca do dispositivo
            + "is_wireless_device%0D%0A" // Se  um dispositivo movel
            + "is_tablet%0D%0A" // Se  um tablet
            + "pointing_method"; // Tipo de metodo de entrada

    // Montagem URL de acesso ao Introspector Servlet WURFL
    urlPath = "http://localhost:8080/AdapterAPI/"; // Caminho do projeto
    urlInicio = "introspector.do?action=Form&form=pippo&ua=" + userAgent;
    urlCapacidades = "&capabilities=" + capacidades;
    urlFim = "&wurflEngineTarget=performance&wurflUserAgentPriority=OverrideSideloadedBrowserUserAgent";

    // Conexo com o Servlet
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(urlPath + urlInicio + urlCapacidades + urlFim);
    getRequest.addHeader("accept", "application/json");

    HttpResponse response = httpClient.execute(getRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }//from w  ww.  j a v  a2s.  c o  m

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String buffer;
    String dados = "";
    //System.out.println("Output from Server .... \n");
    while ((buffer = br.readLine()) != null) {
        dados += buffer;
    }
    //System.out.println("Sada:\n\t" + dados);

    httpClient.getConnectionManager().shutdown();

    JSONObject my_obj;
    JSONParser parser = new JSONParser();
    my_obj = (JSONObject) parser.parse(dados);
    JSONObject capabilities = (JSONObject) my_obj.get("capabilities");

    return capabilities.toJSONString();
}