Example usage for org.apache.http.impl.client DefaultHttpClient execute

List of usage examples for org.apache.http.impl.client DefaultHttpClient execute

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.ssy.havefunweb.util.WeixinUtil.java

public static JSONObject doGetStr(String url) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    JSONObject jsonObject = null;/*w ww . j a  v  a2  s .  c  om*/
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        String result = EntityUtils.toString(entity, "UTF-8");
        jsonObject = JSONObject.fromObject(result);
    }
    return jsonObject;
}

From source file:com.ggasoftware.uitest.utils.FileUtil.java

/**
 * Check file download from url./*from  w w  w .  j  ava  2s. c  o  m*/
 *
 * @param downloadUrl    - url of file to download
 * @param outputFilePath - file path for output
 * @throws Exception - exception
 */
public static void downloadFile(String downloadUrl, String outputFilePath) throws IOException {

    ReporterNGExt.logAction("", "", String.format("Download file form url: %s", downloadUrl));

    CookieStore cookieStore = seleniumCookiesToCookieStore();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setCookieStore(cookieStore);
    HttpGet httpGet = new HttpGet(downloadUrl);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        File outputFile = new File(outputFilePath);
        InputStream inputStream = entity.getContent();
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        int read;
        byte[] bytes = new byte[1024];
        while ((read = inputStream.read(bytes)) != -1) {
            fileOutputStream.write(bytes, 0, read);
        }
        fileOutputStream.close();
        ReporterNGExt.logTechnical(
                String.format("downloadFile: %d bytes. %s", outputFile.length(), entity.getContentType()));
    } else {
        ReporterNGExt.logFailedScreenshot(ReporterNGExt.BUSINESS_LEVEL, "Download failed!");
    }
}

From source file:fr.forexperts.service.DataService.java

private static ArrayList<String[]> getCsvFromUrl(String url) {
    ArrayList<String[]> data = new ArrayList<String[]>();

    try {/*from   w  w w  .jav  a  2s .com*/
        HttpGet httpGet = new HttpGet(url);
        HttpParams httpParameters = new BasicHttpParams();
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));

            String line;
            while ((line = reader.readLine()) != null) {
                String[] price = line.split(",");
                data.add(price);
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return data;
}

From source file:jp.co.conit.sss.sp.ex1.util.HttpUtil.java

/**
 * GET??????/*from   w  w w .  j a va  2s.  c om*/
 * 
 * @param url {@code null}???
 * @return
 */
public static String get(String url) throws Exception {

    if (url == null) {
        throw new IllegalArgumentException("'url' must not be null.");
    }

    String result = null;

    DefaultHttpClient httpclient = new DefaultHttpClient(getHttpParam());
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpclient.execute(httpGet);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        response.getEntity().writeTo(byteArrayOutputStream);
        result = byteArrayOutputStream.toString();
    } catch (ClientProtocolException e) {
        throw new Exception();
    } catch (IllegalStateException e) {
        throw new Exception();
    } catch (IOException e) {
        throw new Exception();
    }

    return result;
}

From source file:com.firewallid.util.FIConnection.java

public static void sendJson(String host, String json) throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(host);

    StringEntity input = new StringEntity(json);
    input.setContentType("application/json");
    postRequest.setEntity(input);/* w w  w.  j  ava2s  .c o m*/

    HttpResponse response = httpClient.execute(postRequest);
}

From source file:com.libresoft.apps.ARviewer.Utils.GeoNames.AltitudeManager.java

public static double getAltitudeFromLatLong(float latitude, float longitude) {
    double altitude = AltitudeManager.NO_ALTITUDE_VALUE;

    String data = "?lat=" + Float.toString(latitude) + "&lng=" + Float.toString(longitude);

    try {//Aster
        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(URL + data);

        HttpResponse response = httpclient.execute(httpGet);

        HttpEntity entity = response.getEntity();

        String str = convertStreamToString(entity.getContent());

        Log.d("GeoNames: ", str);

        altitude = Double.parseDouble(str);

        if (altitude < 0)
            altitude = 0;//from w w  w . j  ava2  s  .co m

        return altitude;

    } catch (Exception e) {
        Log.e("GeoNames: ", e.getMessage());
        return emergencyService(data);
    }
}

From source file:com.libresoft.apps.ARviewer.Utils.GeoNames.AltitudeManager.java

private static double emergencyService(String data) {
    double altitude = AltitudeManager.NO_ALTITUDE_VALUE;
    try {//Gtopo30
        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(URL_B + data);

        HttpResponse response = httpclient.execute(httpGet);

        HttpEntity entity = response.getEntity();

        String str = convertStreamToString(entity.getContent());

        Log.d("GeoNames: ", str);

        altitude = Double.parseDouble(str);

        if (altitude < 0)
            altitude = 0;/*from   ww  w  .j  a  v a 2s.  c  o  m*/

        return altitude;

    } catch (Exception e) {
        Log.e("GeoNames: ", e.getMessage());
        return AltitudeManager.NO_ALTITUDE_VALUE;
    }

}

From source file:io.undertow.integration.test.rootcontext.RootContextUtil.java

/**
 * Access http://localhost//*from  w w w . j a v  a  2s.  c  om*/
 */
public static String hitRootContext(Logger log, URL url, String serverName) throws Exception {
    HttpGet httpget = new HttpGet(url.toURI());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpget.setHeader("Host", serverName);

    log.info("executing request" + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-Exception(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    return EntityUtils.toString(response.getEntity());
}

From source file:att.jaxrs.client.Content_tagCollection.java

public static Content_tagCollection getContentTagsWithID(long content_id) {
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("content_id", Long.toString(content_id)));

    Content_tagCollection collectionCT = new Content_tagCollection();

    try {/*w w  w.  j av a  2 s .  c o  m*/
        System.out.println("invoking getTagsWithID: " + content_id);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.SELECT_WITH_KEY_CONTENT_TAG_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        String resultStr = Util.getStringFromInputStream(result);

        collectionCT = Marshal.unmarshal(Content_tagCollection.class, resultStr);

    } catch (Exception e) {
        e.printStackTrace();

    }

    return collectionCT;
}

From source file:br.pub.tradutor.TradutorController.java

/**
 * Mtodo utilizado para traduo utilizando o Google Translate
 *
 * @param text Texto a ser traduzido//from w ww.  ja  va2  s  .  c  om
 * @param from Idioma de origem
 * @param to Idioma de destino
 * @return Texto traduzido (no idioma destino)
 * @throws IOException
 */
public static String translate(String text, String from, String to) throws IOException {
    //Faz encode de URL, para fazer escape dos valores que vo na URL
    String encodedText = URLEncoder.encode(text, "UTF-8");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //Mtodo GET a ser executado
    HttpGet httpget = new HttpGet(String.format(TRANSLATOR, encodedText, from, to));

    //Faz a execuo
    HttpResponse response = httpclient.execute(httpget);

    //Busca a resposta da requisio e armazena em String
    String returnContent = EntityUtils.toString(response.getEntity());

    //Desconsidera tudo depois do primeiro array
    returnContent = returnContent.split("\\],\\[")[0];

    //StringBuilder que sera carregado o retorno
    StringBuilder translatedText = new StringBuilder();

    //Verifica todas as tradues encontradas, e junta todos os trechos
    Matcher m = RESULTS_PATTERN.matcher(returnContent);
    while (m.find()) {
        translatedText.append(m.group(1).trim()).append(' ');
    }

    //Retorna
    return translatedText.toString().trim();

}