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:groovesquid.GetAdsThread.java

public static String getFile(String url) {
    String responseContent = null;
    HttpEntity httpEntity = null;//from ww w.  ja  va 2s.co  m
    try {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        httpGet.setHeader(HTTP.USER_AGENT,
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse httpResponse = httpClient.execute(httpGet);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        httpEntity = httpResponse.getEntity();

        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity.writeTo(baos);
        } else {
            throw new RuntimeException(url);
        }

        responseContent = baos.toString("UTF-8");
    } catch (Exception ex) {
        log.log(Level.SEVERE, null, ex);
    } finally {
        try {
            EntityUtils.consume(httpEntity);
        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
        }
    }
    return responseContent;
}

From source file:net.felixrabe.unleashthecouch.Utils.java

public static String getDocument(String couchDbDocUrl) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(couchDbDocUrl);
    HttpResponse response = null;/*from   ww w. j  a  va  2  s.co m*/
    try {
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            entity.writeTo(baos);
            return new String(baos.toByteArray(), "UTF-8");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.android.utility.util.Network.java

public static boolean isReachable(String url_string) {
    boolean result = false;
    try {//  w ww. j  av  a  2 s  . co m
        HttpGet request = new HttpGet(url_string);
        HttpParams httpParameters = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse response = httpClient.execute(request);

        int status = response.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            result = true;
        }

    } catch (SocketTimeoutException e) {
        result = false; // this is somewhat expected
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        Logger.e(LogModule.NETWORK, TAG, e.getMessage());
        result = false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Logger.e(LogModule.NETWORK, TAG, e.toString());
        result = false;
    }
    return result;
}

From source file:com.gozap.chouti.service.HttpService.java

/**
 * /*from  w w  w. ja  v a 2 s. com*/
 * @param uri uri
 * @return
 * @author saint
 * @date 2013-4-17
 */
public static byte[] get(String uri) {
    HttpClient httpClient = HttpClientFactory.getInstance();
    HttpGet httpGet = new HttpGet(uri);
    try {
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        byte[] bytes = EntityUtils.toByteArray(httpEntity);
        return bytes;
    } catch (ClientProtocolException e) {
        LOGGER.error("get" + uri + "error", e);
    } catch (IOException e) {
        LOGGER.error("get" + uri + "error", e);
    } finally {
        httpGet.releaseConnection();
    }
    return null;
}

From source file:com.noisepages.nettoyeur.usb.DeviceInfo.java

private static String getName(String url) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    Scanner scanner = new Scanner(response.getEntity().getContent());
    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        int start = line.indexOf("Name:") + 6;
        if (start > 5) {
            int end = line.indexOf("<", start);
            if (end > start) {
                return line.substring(start, end);
            }//from w  ww  .ja v  a  2 s .c o  m
        }
    }
    return null;
}

From source file:org.aectann.postage.TrackingStatusRefreshTask.java

public static TrackingInfo syncRequest(Context context, String tracking) throws FactoryConfigurationError {
    TrackingInfo result = null;//  w  ww  . j av a  2s.  co  m
    if (tracking != null && tracking.length() > 0) {
        tracking = tracking.toUpperCase();
        HttpClient client = new DefaultHttpClient();
        try {
            HttpResponse response = client.execute(new HttpGet("http://prishlo.li/" + tracking + ".xml"));
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream content = response.getEntity().getContent();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(content);
                String weight = getFirstVaueOrNull(document, "weight");
                String from = getFirstVaueOrNull(document, "from");
                String kind = getFirstVaueOrNull(document, "kind");
                TrackingInfo old = TrackingStorageUtils.loadStoredTrackingInfo(tracking, context);
                result = new TrackingInfo(old != null ? old.getName() : null, tracking, weight, kind, from);
                NodeList checkpoints = document.getElementsByTagName("checkpoint");

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                for (int i = 0; i < checkpoints.getLength(); i++) {
                    Node current = checkpoints.item(i);
                    NamedNodeMap attributes = current.getAttributes();
                    Node state = attributes.getNamedItem("state");
                    Node attribute = attributes.getNamedItem("attribute");
                    Node date = attributes.getNamedItem("date");

                    String dateString = date.getNodeValue();
                    String attributeString = attribute.getNodeValue();
                    String stateString = state.getNodeValue();
                    String locationString = current.getFirstChild().getNodeValue();
                    result.addStatus(new TrackingStatus(stateString, dateFormat.parse(dateString),
                            attributeString, locationString));
                }
            }
        } catch (Exception e) {
            if (result == null) {
                result = new TrackingInfo(null, tracking, null, null, null);
            }
        }
    }
    return result;
}

From source file:Main.java

public static String getJSONFromUrlWithPostRequest(String url, List<NameValuePair> params) {

    try {//from w  w w.ja  va  2  s.com
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        String tempResponse = EntityUtils.toString(httpResponse.getEntity());

        return tempResponse;

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

    return "";
}

From source file:com.zyf.bike.suzhou.utils.HttpOperation.java

/**
 * Http Get??// w ww  .  j a  va 2 s .  c  om
 * @param url
 * @param testnum ?
 * @return
 */
public static byte[] doGetBase(String url, int testnum) {
    if (testnum < 0) {
        return null;
    }
    try {
        //HttpClient    
        HttpClient httpclient = new DefaultHttpClient();
        //POST  
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpclient.execute(get);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            //?
            return EntityUtils.toByteArray(response.getEntity());
        } else if (code == HttpStatus.SC_NOT_FOUND || code == HttpStatus.SC_FORBIDDEN
                || code == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            //403 ?
            //404 ??
            //405 ??
            return null;
        } else {
            //??
            doGetBase(url, testnum--);
        }
    } catch (Exception e) {
        Logger.e(TAG, e.getMessage(), e);
    }
    return null;
}

From source file:org.angellist.angellistmobile.ApiCalls.java

private static String GetData(String url) {
    byte[] result = null;
    String str = "";
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    try {/*www  .  ja v a2s . com*/

        HttpResponse response = client.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
            result = EntityUtils.toByteArray(response.getEntity());
            str = new String(result, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return str;

}

From source file:org.openqa.selenium.remote.server.SessionLogsTest.java

private static JSONObject getValueForPostRequest(URL serverUrl) throws Exception {
    String postRequest = serverUrl + "/logs";
    HttpClient client = new DefaultHttpClient();
    HttpPost postCmd = new HttpPost(postRequest);
    HttpResponse response = client.execute(postCmd);
    HttpEntity entity = response.getEntity();
    InputStreamReader reader = new InputStreamReader(entity.getContent(), Charsets.UTF_8);
    try {/* ww w .j a  va2  s  . c o m*/
        String str = CharStreams.toString(reader);
        return new JSONObject(str).getJSONObject("value");
    } finally {
        EntityUtils.consume(entity);
        reader.close();
    }
}