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:revServTest.IoTTestForPUT.java

public String testPut(String url0, StringEntity input) {
    String result;/* ww w .ja  v  a  2 s . co m*/
    HttpResponse response = null;
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPut putRequest = new HttpPut(url0);

        input.setContentType("application/xml");
        putRequest.setEntity(input);

        response = httpClient.execute(putRequest);

        if (response.getStatusLine().getStatusCode() != 409 && response.getStatusLine().getStatusCode() != 201
                && response.getStatusLine().getStatusCode() != 400
                && response.getStatusLine().getStatusCode() != 200
                && response.getStatusLine().getStatusCode() != 404
                && response.getStatusLine().getStatusCode() != 500) {
            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) {
            System.out.println(output);
        }
        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    //      if (response.getStatusLine().getStatusCode() == 409 || response.getStatusLine().getStatusCode() == 201 || response.getStatusLine().getStatusCode() == 400
    //            || response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 404 || response.getStatusLine().getStatusCode() == 500) {
    //
    //         result = RevocationOutCome.code;
    //
    //      } else {
    //         String res = Integer.toString(response.getStatusLine().getStatusCode());
    //         result = res;
    //      }
    //      return result;
    return RevocationOutCome.code;

}

From source file:net.zypr.api.Protocol.java

public JSONObject doGetJSON(String url) throws APICommunicationException, APIProtocolException {
    Session.getInstance().addActiveRequestCount();
    long t1 = System.currentTimeMillis();
    JSONObject jsonObject = null;//from  ww w.jav  a  2s. com
    JSONParser jsonParser = new JSONParser();
    try {
        DefaultHttpClient httpclient = getHTTPClient();
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        if (httpResponse.getStatusLine().getStatusCode() != 200)
            throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode()
                    + " - " + httpResponse.getStatusLine().getReasonPhrase() + " at " + url);
        HttpEntity httpEntity = httpResponse.getEntity();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
        jsonObject = (JSONObject) jsonParser.parse(bufferedReader);
        bufferedReader.close();
        httpclient.getConnectionManager().shutdown();
    } catch (ParseException parseException) {
        throw new APIProtocolException(parseException);
    } catch (IOException ioException) {
        throw new APICommunicationException(ioException);
    } catch (ClassCastException classCastException) {
        throw new APIProtocolException(classCastException);
    } catch (IllegalArgumentException illegalArgumentException) {
        throw new APICommunicationException(illegalArgumentException);
    } finally {
        Session.getInstance().removeActiveRequestCount();
        long t2 = System.currentTimeMillis();
        Debug.print(url + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : " + jsonObject);
    }
    return (jsonObject);
}

From source file:org.droidkit.app.UpdateService.java

private boolean updateVersion(String apk) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(apk);
    boolean result = false;

    try {/*from   w w  w .  ja  va2s . com*/
        HttpResponse response = client.execute(get);
        InputStream in = response.getEntity().getContent();

        File localFile = new File(
                Environment.getExternalStorageDirectory() + "/" + apk.substring(apk.lastIndexOf("/") + 1));
        FileOutputStream out = new FileOutputStream(localFile);
        int count;
        byte[] buffer = new byte[8196];

        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }

        out.close();
        in.close();
        result = true;
    } catch (ClientProtocolException e) {
        Log.e("DroidKit", "Error retrieving updated apk: " + e.toString());
    } catch (IOException e) {
        Log.e("DroidKit", "Error retrieving updated apk: " + e.toString());
    }

    client.getConnectionManager().shutdown();
    return result;
}

From source file:org.jboss.as.test.integration.web.security.basic.WebSecurityBASICTestCase.java

@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from  w  ww.  jav  a  2  s . c  o  m
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } 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:org.openml.knime.OpenMLWebservice.java

/**
 * Upload an implementation./*from   w ww .ja  v a 2s . com*/
 * 
 * 
 * @param description Implementation description file
 * @param workflow Workflow file
 * @param user Name of the user
 * @param password Password of the user
 * @return Response from the server
 * @throws Exception If communication failed
 */
public static String sendImplementation(final File description, final File workflow, final String user,
        final String password) throws Exception {
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80);
        httpclient.getCredentialsProvider().setCredentials(scope, credentials);
        String url = WEBSERVICEURL + "?f=openml.implementation.upload";
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
        FileBody descBin = new FileBody(description);
        reqEntity.addPart("description", descBin);
        FileBody workflowBin = new FileBody(workflow);
        reqEntity.addPart("source", workflowBin);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() < 200) {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        if (resEntity != null) {
            result = convertStreamToString(resEntity.getContent());
        }
        ErrorDocument errorDoc = null;
        try {
            errorDoc = ErrorDocument.Factory.parse(result);
        } catch (Exception e) {
            // no error XML should mean no error
        }
        if (errorDoc != null && errorDoc.validate()) {
            ErrorDocument.Error error = errorDoc.getError();
            String errorMessage = error.getCode() + " : " + error.getMessage();
            if (error.isSetAdditionalInformation()) {
                errorMessage += " : " + error.getAdditionalInformation();
            }
            throw new Exception(errorMessage);
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
            // ignore
        }
    }
    return result;
}

From source file:com.kkurahar.locationmap.HttpConnection.java

public String doGet(String url) {

    HttpGet method = new HttpGet(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    method.setHeader("Connection", "Keep-Alive");
    try {/* www .  ja  v a  2  s  . c o  m*/

        String resultRes = httpClient.execute(method, new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // Xe?[^XR?[h
                int status = response.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK == status) {
                    Header[] headers = response.getAllHeaders();
                    for (Header h : headers) {
                        System.out.println(h.getName() + ":" + h.getValue());
                    }
                } else {
                    throw new RuntimeException("?MG?[?");
                }
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        });
        return resultRes;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:monakhv.samlib.http.HttpClientController.java

/**
 * Very row method to make http connection and begin download data Call only
 * by _getURL/* w w w  .j  a  v  a2  s .c  o  m*/
 *
 * @param url URL to download
 * @param reader File to download to can be null
 * @return Download data if "f" is null
 * @throws IOException connection problem
 * @throws SamLibIsBusyException host return 503 status
 * @throws SamlibParseException host return status other then 200 and 503
 */
private String __getURL(URL url, PageReader reader)
        throws IOException, SamLibIsBusyException, SamlibParseException {

    HttpGet method = new HttpGet(url.toString());

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);

    DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);

    if (pwd != null && scope != null) {
        httpclient.getCredentialsProvider().setCredentials(scope, pwd);
    }

    if (proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    method.setHeader("User-Agent", USER_AGENT);
    method.setHeader("Accept-Charset", ENCODING);
    HttpResponse response;
    try {
        response = httpclient.execute(method);
        Log.d(DEBUG_TAG, "Status Response: " + response.getStatusLine().toString());
    } catch (NullPointerException ex) {
        Log.e(DEBUG_TAG, "Connection Error", ex);
        throw new IOException("Connection error: " + url.toString());
    }
    int status = response.getStatusLine().getStatusCode();

    if (status == 503) {
        httpclient.getConnectionManager().shutdown();
        throw new SamLibIsBusyException("Need to retryException ");
    }
    if (status != 200) {
        httpclient.getConnectionManager().shutdown();
        throw new SamlibParseException("Status code: " + status);
    }

    String result = reader.doReadPage(response.getEntity().getContent());
    httpclient.getConnectionManager().shutdown();
    return result;

}

From source file:io.undertow.server.handlers.encoding.RequestContentEncodingTestCase.java

public void runTest(final String theMessage, String encoding) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    try {/* w  w w .  j a va2  s  . c  om*/
        message = theMessage;
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/encode");
        get.setHeader(Headers.ACCEPT_ENCODING_STRING, encoding);
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
        Assert.assertEquals(encoding, header[0].getValue());
        byte[] body = HttpClientUtils.readRawResponse(result);

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/decode");
        post.setEntity(new ByteArrayEntity(body));
        post.addHeader(Headers.CONTENT_ENCODING_STRING, encoding);

        result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String sb = HttpClientUtils.readResponse(result);
        Assert.assertEquals(theMessage.length(), sb.length());
        Assert.assertEquals(theMessage, sb);

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:net.zypr.api.Protocol.java

public byte[] doGetBytes(String url) throws APICommunicationException {
    Session.getInstance().addActiveRequestCount();
    long t1 = System.currentTimeMillis();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {/*from w  w w  . ja  v  a2 s. c om*/
        DefaultHttpClient httpclient = getHTTPClient();
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        if (httpResponse.getStatusLine().getStatusCode() != 200)
            throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode()
                    + " - " + httpResponse.getStatusLine().getReasonPhrase() + " at " + url);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream inputStream = httpEntity.getContent();
        byte[] buffer = new byte[4096];
        int readCount = 0;
        while ((readCount = inputStream.read(buffer)) != -1)
            byteArrayOutputStream.write(buffer, 0, readCount);
        httpclient.getConnectionManager().shutdown();
    } catch (IOException ioException) {
        throw new APICommunicationException(ioException);
    } finally {
        Session.getInstance().removeActiveRequestCount();
        long t2 = System.currentTimeMillis();
        Debug.print(url + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : " + byteArrayOutputStream.size()
                + " bytes");
    }
    return (byteArrayOutputStream.toByteArray());
}

From source file:conexao.Conexao.java

public PlayerGames getPlayerGames(Long summonerId) {
    PlayerGames example = null;//from   w w  w.  j  a  va 2 s .  c  om
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("https://br.api.pvp.net/api/lol/br/v1.3/game/by-summoner/" + summonerId
                + "/recent?api_key=RGAPI-6b21c1fe-67a3-4222-b713-918d6609f30c");
        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) {
        System.out.println(output);
        }*/

        do {
            output += br.readLine();
        } while (br.readLine() != null);
        // System.out.println("output: " + output);
        example = new Gson().fromJson(output, PlayerGames.class);
        httpClient.getConnectionManager().shutdown();
        // System.out.println("id: " + example.getSummonerId());
    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return example;
}