Example usage for org.apache.http.client HttpClient execute

List of usage examples for org.apache.http.client HttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient execute.

Prototype

<T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
        throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context and processes the response using the given response handler.

Usage

From source file:com.hichinaschool.flashcards.anki.web.HttpFetcher.java

public static String fetchThroughHttp(String address, String encoding) {

    try {/*from  w  w w . j a v a2s  .  c o  m*/
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(address);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        if (!response.getStatusLine().toString().contains("OK")) {
            return "FAILED";
        }

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), Charset.forName(encoding)));

        StringBuilder stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }

        return stringBuilder.toString();

    } catch (Exception e) {
        return "FAILED with exception: " + e.getMessage();
    }

}

From source file:oracle.custom.ui.oauth.vo.OpenIdConfiguration.java

public static OpenIdConfiguration getInstance(String tenantName) throws Exception {
    if (configMap.containsKey(tenantName.toLowerCase())) {
        return configMap.get(tenantName.toLowerCase());
    }// ww  w  .  j a  v  a2 s.  co m
    String url = ServerUtils.getIDCSBaseURL(tenantName) + endpoint;
    System.out.println("URL for tenant '" + tenantName + "' is '" + url + "'");
    HttpClient client = ServerUtils.getClient(tenantName);
    URI uri = new URI(url);
    HttpGet get = new HttpGet(uri);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpResponse response = client.execute(host, get);
    try {
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        //res = res.replaceAll("secureoracle.idcs.internal.oracle.com:443", "oc-140-86-12-131.compute.oraclecloud.com");
        OpenIdConfiguration openIdConfigInstance = mapper.readValue(res, OpenIdConfiguration.class);

        configMap.put(tenantName.toLowerCase(), openIdConfigInstance);
        return openIdConfigInstance;
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
}

From source file:com.github.rnewson.couchdb.lucene.couchdb.HttpUtils.java

public static final int put(final HttpClient httpClient, final String url, final String body)
        throws IOException {
    final HttpPut put = new HttpPut(url);
    if (body != null) {
        put.setHeader("Content-Type", Constants.APPLICATION_JSON);
        put.setEntity(new StringEntity(body, "UTF-8"));
    }// w  ww.j a va  2 s  . c om
    return httpClient.execute(put, new StatusCodeResponseHandler());
}

From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java

static byte[] loadHTTPArchive(final String url) throws IOException {
    final HttpClient client = HttpClientBuilder.create().build();
    final HttpContext context = HttpClientContext.create();
    final HttpGet get = new HttpGet(url);
    final HttpResponse response = client.execute(get, context);

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        InputStream in = null;//  w w  w .  j  a va 2 s.  c o  m
        try {
            final HttpEntity entity = response.getEntity();
            in = entity.getContent();
            final byte[] data = entity.getContentLength() < 0L ? IOUtils.toByteArray(entity.getContent())
                    : IOUtils.toByteArray(entity.getContent(), entity.getContentLength());
            return data;
        } finally {
            IOUtils.closeQuietly(in);
        }
    } else {
        throw new IOException("Can't download from http '" + url + "' code [" + url + ']');
    }
}

From source file:com.github.horrorho.inflatabledonkey.chunk.engine.ChunkClient.java

public static <T> Optional<T> fetch(HttpClient httpClient, ChunkServer.StorageHostChunkList chunkList,
        Function<ChunkServer.StorageHostChunkList, HttpUriRequest> chunkListRequestFactory,
        ResponseHandler<T> responseHandler) {

    try {/*from w ww .  java2 s  .  c  om*/
        HttpUriRequest request = chunkListRequestFactory.apply(chunkList);
        T data = httpClient.execute(request, responseHandler);
        return Optional.of(data);

    } catch (IOException ex) {
        logger.warn("-- fetch() - IOException: {}", ex);
        return Optional.empty();
    }
}

From source file:com.qweex.callisto.Live.java

/** Sends an error report to the folks at Qweex. COMPLETELY anonymous. The only information that is sent is the version of Callisto and the version of Android. */
public static void SendErrorReport(String msg) {
    String errorReport = errorReportURL + "?id=Callisto&v=" + StaticBlob.appVersion + "&err="
            + android.os.Build.VERSION.RELEASE + "_" + msg;
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(errorReport);
    try {/*from   w  w  w .ja v a 2 s . c  o  m*/
        httpClient.execute(httpGet, localContext);
    } catch (Exception e) {
    }
}

From source file:io.milton.httpclient.Utils.java

public static HttpResult executeHttpWithResult(HttpClient client, HttpUriRequest m, OutputStream out,
        HttpContext context) throws IOException {
    HttpResponse resp = client.execute(m, context);
    HttpEntity entity = resp.getEntity();
    if (entity != null) {
        InputStream in = null;/*from  ww  w .  j a  v a 2s  .  co  m*/
        try {
            in = entity.getContent();
            if (out != null) {
                IOUtils.copy(in, out);
            }
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
    Map<String, String> mapOfHeaders = new HashMap<String, String>();
    Header[] respHeaders = resp.getAllHeaders();
    for (Header h : respHeaders) {
        mapOfHeaders.put(h.getName(), h.getValue()); // TODO: should concatenate multi-valued headers
    }
    HttpResult result = new HttpResult(resp.getStatusLine().getStatusCode(), mapOfHeaders);
    return result;
}

From source file:org.syphr.mythtv.ws.impl.ServiceUtils.java

public static String getVersion(URI serviceBaseUri) throws IOException {
    URI uri = URI.create(serviceBaseUri.toString() + "/" + VERSION_URI_PATH);

    HttpClient httpclient = new DefaultHttpClient();
    try {//from w  w w .  ja va  2 s.  c o  m
        HttpGet httpget = new HttpGet(uri);
        LOGGER.debug("Retrieving service version from {}", httpget.getURI());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        LOGGER.trace("Version response: {}", responseBody);

        Matcher matcher = VERSION_PATTERN.matcher(responseBody);
        if (matcher.matches()) {
            return matcher.group(1);
        }

        throw new IOException("Failed to retrieve version information");
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:Main.java

private static void ExecutePostRequest(HttpClient client, HttpRequestBase method,
        ResponseHandler<String> responseHandler) {
    BasicHttpResponse errorResponse = new BasicHttpResponse(new ProtocolVersion("HTTP_ERROR", 1, 1), 500,
            "ERROR");

    try {/*from   w  w w . j ava 2  s .  c om*/
        client.execute(method, responseHandler);
    } catch (Exception e) {
        errorResponse.setReasonPhrase(e.getMessage());
        try {
            responseHandler.handleResponse(errorResponse);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.lazydevs.api.gog.util.HttpClientUtil.java

public static HttpResponse post(HttpClient client, HttpContext context, String url,
        List<NameValuePair> params) {

    HttpPost post = new HttpPost(url);
    HttpResponse response;//w  ww.ja  va 2s. c o  m

    post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

    try {
        response = client.execute(post, context);
    } catch (IOException e) {
        throw new GogApiException("Error executing POST request. url=" + url, e);
    }

    return response;
}