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:fr.pingtimeout.ConnectionUtils.java

public static boolean pressLeftOnServer(String serverHostname) {
    String pingUrlAsString = String.format("http://%s:8080/left", serverHostname);
    Log.d(loggerName, "Triggering a LEFT keystroke on server using " + pingUrlAsString);

    BufferedReader bufferedReader = null;
    try {/*  www  .  jav a 2 s.  c o  m*/
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(new URI(pingUrlAsString));

        HttpResponse response = client.execute(request);

        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while (bufferedReader.readLine() != null) {
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ignored) {
            }
        }
    }

    return true;
}

From source file:uk.ac.bbsrc.tgac.miso.core.util.TaxonomyUtils.java

public static String checkScientificNameAtNCBI(String scientificName) {
    try {/*from  w w  w  .  j  a v  a  2  s  .  c o  m*/
        String query = ncbiEntrezUtilsURL + "db=taxonomy&term=" + URLEncoder.encode(scientificName, "UTF-8");
        final HttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(query);
        try {
            HttpResponse response = httpclient.execute(httpget);
            String out = parseEntity(response.getEntity());
            log.info(out);
            try {
                DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document d = docBuilder.newDocument();

                TransformerFactory.newInstance().newTransformer()
                        .transform(new StreamSource(new UnicodeReader(out)), new DOMResult(d));

                NodeList nl = d.getElementsByTagName("Id");
                for (int i = 0; i < nl.getLength(); i++) {
                    Element e = (Element) nl.item(i);
                    return e.getTextContent();
                }
            } catch (ParserConfigurationException e) {
                log.error("check scientific name at NCBI", e);
            } catch (TransformerException e) {
                log.error("check scientific name at NCBI", e);
            }
        } catch (ClientProtocolException e) {
            log.error("check scientific name at NCBI", e);
        } catch (IOException e) {
            log.error("check scientific name at NCBI", e);
        }
    } catch (UnsupportedEncodingException e) {
        log.error("check scientific name at NCBI", e);
    }
    return null;
}

From source file:Main.java

/**
 * Performs an HTTP Post request to the specified url with the
 * specific HttpEntity, and return the string from the HttpResponse.
 * @param url The web address to post the request to
 * @param httpEntity The entity to send via the request
 * @return The result string of the request
 * @throws Exception/*ww w .j  a  va  2  s . com*/
 */
public static String executeHttpPost(String url, HttpEntity entity) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        request.setEntity(entity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:fr.pingtimeout.ConnectionUtils.java

public static boolean pressRightOnServer(String serverHostname) {
    String pingUrlAsString = String.format("http://%s:8080/right", serverHostname);
    Log.d(loggerName, "Triggering a RIGHT keystroke on server using " + pingUrlAsString);

    BufferedReader bufferedReader = null;
    try {/* w w w.  j av a2 s  .c o m*/
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(new URI(pingUrlAsString));

        HttpResponse response = client.execute(request);

        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while (bufferedReader.readLine() != null) {
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {

        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ignored) {
            }
        }
    }

    return true;
}

From source file:com.pyz.tool.weixintool.util.HttpTool.java

/**
 * get  url ?/*from w w w .ja v a  2 s. co m*/
 * @param url
 * @return
 * @throws Exception
 */
public static String request(String url) throws Exception {
    String result = "";
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse httpresponse = httpClient.execute(httpget);
        HttpEntity entity = httpresponse.getEntity();
        result = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.quackware.handsfreemusic.YouTubeUtility.java

public static String calculateYouTubeUrl(String youtubeVideoId)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    HttpGet getMethod = new HttpGet(YOUTUBE_VIDEO_INFORMATION_URL + youtubeVideoId);
    HttpResponse response = null;//from  ww w. j  av a 2  s.  com

    response = client.execute(getMethod);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    String infoStr = null;
    response.getEntity().writeTo(bos);
    infoStr = new String(bos.toString("UTF-8"));

    String[] args = infoStr.split("&");
    Map<String, String> argMap = new HashMap<String, String>();
    for (int i = 0; i < args.length; i++) {
        String[] argValStrArr = args[i].split("=");
        if (argValStrArr != null) {
            if (argValStrArr.length >= 2) {
                argMap.put(argValStrArr[0], URLDecoder.decode(argValStrArr[1]));
            }
        }
    }
    String tokenStr = null;
    try {
        tokenStr = URLDecoder.decode(argMap.get("token"));
    } catch (Exception ex) {
        return null;
    }
    String uriStr = "http://www.youtube.com/get_video?video_id=" + youtubeVideoId + "&t="
            + URLEncoder.encode(tokenStr) + "&fmt=18";
    return uriStr;
}

From source file:com.codeskraps.lolo.misc.Utils.java

public static LOLO getLolo() throws UnsupportedEncodingException, ClientProtocolException, IOException,
        IllegalArgumentException, NullPointerException, JSONException {
    long startTime = System.currentTimeMillis();
    if (BuildConfig.DEBUG)
        Log.d(TAG, "download begining");
    if (BuildConfig.DEBUG)
        Log.d(TAG, "download url:" + Constants.LOLO_URL);

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);

    HttpClient client = new DefaultHttpClient(httpParameters);
    HttpGet request = new HttpGet(Constants.LOLO_URL);
    HttpResponse response = client.execute(request);

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();
    Log.d(TAG, "json: " + json);
    reader.close();/*  ww w  .ja  va 2s  .  c  om*/

    JSONTokener tokener = new JSONTokener(json);

    JSONObject finalResult = new JSONObject(tokener);
    LOLO lolo = finalResult.getBoolean("open") ? LOLO.ON : LOLO.OFF;

    if (BuildConfig.DEBUG)
        Log.d(TAG, "lolo: " + lolo);
    if (BuildConfig.DEBUG)
        Log.d(TAG, "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
    return lolo;
}

From source file:org.openvoters.android.tasks.RemoteAPIVoteTask.java

public static HttpResponse makeRequest(String path, Item item, String uniqueID) throws Exception {
    JSONObject holder = new JSONObject();
    holder.put("candidate", item.getID());
    holder.put("ID", uniqueID);

    int TIMEOUT_MILLISEC = 10000;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(path);
    request.setEntity(new ByteArrayEntity(holder.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(request);
    return response;
}

From source file:org.kegbot.app.util.Downloader.java

/**
 * Downloads and returns a URL as a {@link Bitmap}.
 *
 * @param url the image to download/*from   w  ww  .  j a v  a2  s  . co m*/
 * @return a new {@link Bitmap}, or {@code null} if any error occurred
 */
public static Bitmap downloadBitmap(String url) {
    final HttpClient client = new DefaultHttpClient();
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;

                inputStream = entity.getContent();
                return BitmapFactory.decodeStream(inputStream, null, options);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return null;
}

From source file:nl.coralic.beta.sms.utils.http.HttpHandler.java

private static Response doPost(String url, List<NameValuePair> postdata) {
    HttpClient httpclient = getHttpClient();
    try {//w ww . j av  a 2 s .  c  om
        HttpPost httpost = new HttpPost(url);
        httpost.setEntity(new UrlEncodedFormEntity(postdata, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httpost);
        if (response.getStatusLine().getStatusCode() == 200) {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            return new Response(responseHandler.handleResponse(response));
        } else {
            return new Response(R.string.ERR_PROV_NO_RESP);
        }
    } catch (Exception e) {
        return new Response(R.string.ERR_CONN_ERR);
    } finally {
        // Release the resources
        httpclient.getConnectionManager().shutdown();
    }
}