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

HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context.

Usage

From source file:eu.skillpro.ams.pscm.connector.amsservice.ui.GetConfigurationHandler.java

/**
 * @param approved if only approved configuration should be called or not
 * @return a map ... /*from  w ww .j ava 2  s.  c  o m*/
 * @throws ClientProtocolException
 * @throws IOException
 */
public static Map<String, List<AssetTO>> getConfiguration(boolean approved)
        throws ClientProtocolException, IOException {
    String serviceName = "getNewConfiguration";
    if (approved) {
        serviceName = "getApprovedConfiguration";
    }
    HttpGet request = new HttpGet(AMSServiceUtility.serviceAddress + serviceName);
    System.out.println(request.getRequestLine() + " =====================================");
    request.setHeader("Content-type", "application/json");

    HttpClient client = HttpClientBuilder.create().build();
    ;
    HttpResponse response = client.execute(request);

    System.out.println("Response status: " + response.getStatusLine().getStatusCode());
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
        break;
    }
    Map<String, List<AssetTO>> result = JSONUtility.convertToMap(line,
            new TypeToken<Map<String, List<AssetTO>>>() {
            }.getType());
    return result;
}

From source file:org.artags.android.app.widget.HttpUtils.java

/**
 * Load a bitmap/*from  w  w w  . ja v  a2  s .c  o  m*/
 * @param url The URL
 * @return The bitmap
 */
public static Bitmap loadBitmap(String url) {
    try {
        final HttpClient httpClient = getHttpClient();
        final HttpResponse resp = httpClient.execute(new HttpGet(url));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);
        // Decode the bytes and return the bitmap.
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        decodeOptions.inSampleSize = 1;
        return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
    } catch (Exception e) {
        Log.w(TAG, "Problem while loading image: " + e.toString(), e);
    }
    return null;

}

From source file:au.org.ala.bhl.service.WebServiceHelper.java

/**
 * Performs a GET on the specified URI, and returns the body without any transformation
 * // www .ja v  a2s .com
 * @param uri
 * @return
 * @throws IOException
 */
public static String getText(String uri) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(uri);
    httpget.setHeader("Accept", "application/text");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        @SuppressWarnings("unchecked")
        List<String> lines = IOUtils.readLines(instream, "utf-8");
        return StringUtils.join(lines, "\n");
    }
    return null;
}

From source file:com.tianya.ClientMultipartFormPost.java

public static void preGet(HttpClient httpClient) throws ClientProtocolException, IOException {
    String url = "http://letushow.com/submit";
    HttpGet getReq = new HttpGet(url);

    HttpResponse res = httpClient.execute(getReq);

    getCsrfToken(res);/*from  w w w.  j  a v  a2 s . c  om*/

    EntityUtils.consume(res.getEntity());
}

From source file:org.phpmaven.pear.impl.Helper.java

/**
 * Returns the binary file contents.//from   w w w .j a va2s  . co  m
 * @param uri URI of the resource.
 * @return the files content.
 * @throws IOException thrown on errors.
 */
public static byte[] getBinaryFileContents(String uri) throws IOException {
    // is it inside the local filesystem?
    if (uri.startsWith("file://")) {
        final File channelFile = new File(uri.substring(7));

        final byte[] result = new byte[(int) channelFile.length()];
        final FileInputStream fis = new FileInputStream(channelFile);
        fis.read(result);
        return result;
    }

    // try http connection
    final HttpClient client = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet(uri);
    final HttpResponse response = client.execute(httpget);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Invalid http status: " + response.getStatusLine().getStatusCode() + " / "
                + response.getStatusLine().getReasonPhrase());
    }
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new IOException("Empty response.");
    }
    return EntityUtils.toByteArray(entity);
}

From source file:com.byteridge.bookcircle.framework.listener.ResponseParser.java

public static Reviews GetBooksOnShelf(String shelfName, String userId, int page) throws Exception {
    Uri.Builder builder = new Uri.Builder();
    builder.scheme("http");
    builder.authority("www.goodreads.com");
    builder.path("review/list/" + userId + ".xml");
    builder.appendQueryParameter("key", _ConsumerKey);
    builder.appendQueryParameter("shelf", shelfName);
    builder.appendQueryParameter("v", "2");
    builder.appendQueryParameter("sort", "date_updated");
    builder.appendQueryParameter("order", "d");
    builder.appendQueryParameter("page", Integer.toString(page));
    HttpGet getBooksOnShelfRequest = new HttpGet(builder.build().toString());
    if (get_IsAuthenticated()) {
        _Consumer.sign(getBooksOnShelfRequest);
    }/*from  w w  w  .ja  v  a 2  s .  c o  m*/

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response;

    response = httpClient.execute(getBooksOnShelfRequest);
    Response responseData = ResponseParser.parse(response.getEntity().getContent());
    return responseData.get_Reviews();

}

From source file:com.drismo.logic.JsonFunctions.java

/**
 * Borrowed from:// ww w .  j  av a 2 s . co  m
 * http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
 * and slightly modified.
 * @param url the url to get JSON data from
 * @return the JSONObject containing all the info.
 */
public static JSONObject getJSONfromURL(String url) {
    //initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;
    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    //convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    //try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
    return jArray;
}

From source file:com.github.caldav4j.support.HttpClientTestUtils.java

public static <R, M extends HttpRequestBase, E extends Exception> R executeMethod(int expectedStatus,
        HttpClient httpClient, M method, HttpMethodCallback<R, M, E> methodCallback) throws IOException, E {
    try {//from w  w w  . j  av  a 2 s .  c  o  m
        HttpResponse response = httpClient.execute(method);
        int actualStatus = response.getStatusLine().getStatusCode();
        assertEquals("Response status", expectedStatus, actualStatus);
        if (methodCallback != null)
            return methodCallback.getResponse(method, response);
        else
            return null;
    } finally {
        method.reset();
    }
}

From source file:org.openbase.bco.ontology.lib.commun.monitor.ServerConnection.java

/**
 * Method creates a monitoring thread to observe the connection state between ontology manager and ontology server. In case the server can't be
 * reached, an observable informs./* w ww  .j  a va  2 s.c om*/
 *
 * @throws NotAvailableException is thrown in case there is no thread available.
 */
public static void newServerConnectionObservable() throws NotAvailableException {
    GlobalScheduledExecutorService.scheduleWithFixedDelay(() -> {
        try {
            try {
                final HttpClient httpclient = HttpClients.createDefault();
                final HttpGet httpGet = new HttpGet(OntConfig.getOntologyPingUrl());
                final HttpResponse httpResponse = httpclient.execute(httpGet);

                SparqlHttp.checkHttpRequest(httpResponse, null);
                SERVER_STATE_OBSERVABLE.notifyObservers(ConnectionState.CONNECTED);
            } catch (IOException | CouldNotPerformException ex) {
                SERVER_STATE_OBSERVABLE.notifyObservers(ConnectionState.DISCONNECTED);
            }
        } catch (CouldNotPerformException ex) {
            ExceptionPrinter.printHistory(ex, LOGGER, LogLevel.ERROR);
        }
    }, 0, 1, TimeUnit.SECONDS);
}

From source file:com.othermedia.exampleasyncimage.AsyncImageDemo.java

public static String stringFromURL(String address) throws Exception {

    StringBuilder result = new StringBuilder();
    URL url = new URL(address);
    HttpGet httpRequest = new HttpGet(url.toURI());
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity());
    InputStream input = bufHttpEntity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));

    String line;/*ww  w  . j av a2 s .c om*/
    while ((line = reader.readLine()) != null) {
        result.append(line);
    }
    reader.close();

    return result.toString();
}