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:org.wwscc.registration.attendance.Attendance.java

/**
 * Retrieve the attendance report from the main host
 * @param host the hostname to retrieve from
 * @throws IOException //from w w w  .j  a  v a2  s  .  c  om
 * @throws URISyntaxException 
 * @throws UnsupportedEncodingException 
 */
public static void getAttendance(String host) throws IOException, URISyntaxException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpclient.getParams(), "Scorekeeper/2.0");

    MonitorProgressStream monitor = new MonitorProgressStream("Download Attendance");
    monitor.setProgress(1);
    monitor.setNote("Initialize");

    HttpPost request = new HttpPost(new URI("http", host, "/history/attendance", null));
    File temp = File.createTempFile("attendance", "tmp");
    monitor.setProgress(2);
    monitor.setNote("Connecting/Calcuation...");

    HttpEntity download = httpclient.execute(request).getEntity();
    monitor.setProgress(3);
    monitor.setNote("Downloading...");

    FileOutputStream todisk = new FileOutputStream(temp);
    monitor.setStream(todisk, download.getContentLength());
    download.writeTo(monitor);
    FileUtils.copyFile(temp, defaultfile);
}

From source file:org.apache.drill.test.framework.Utils.java

/**
 * Saves content of existing drill storage plugins.
 * //from   w  w  w  .  j av a  2s . c  o  m
 * @param ipAddress
 *          IP address of node to update storage plugin for
 * @param pluginType
 *          type of plugin; e.g.: "dfs", "cp"
 * @return content of the specified plugin
 * @throws Exception
 */
public static String getExistingDrillStoragePlugin(String ipAddress, String pluginType) throws IOException {
    StringBuilder builder = new StringBuilder();
    builder.append("http://" + ipAddress + ":8047/storage/" + pluginType);
    HttpUriRequest request = new HttpGet(builder.toString() + ".json");
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(request);
    return getHttpResponseAsString(response);
}

From source file:com.fpmislata.productocategoriasjson.ProductoClienteTest.java

private static void deleteProducto(String url) {
    try {//ww  w. j a va  2s  .c  om
        // Crea el producto para realizar la conexion
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // Crea el mtodo con el que va a realizar la operacion
        HttpDelete delete = new HttpDelete(url);
        // Aade las cabeceras al metodo
        delete.addHeader("accept", "application/json; charset=UTF-8");
        delete.addHeader("Content-type", "application/json; charset=UTF-8");
        // Invocamos el servicio rest y obtenemos la respuesta
        HttpResponse response = httpClient.execute(delete);
        String status = response.getStatusLine().toString();

        // Comprobamos si ha fallado
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        } else {
            System.out.println("Se ha eliminado la producto correctamente.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fpmislata.clientecategoriasjson.ClienteClienteTest.java

private static void deleteCliente(String url) {
    try {//from  ww  w  .  j  a v a  2 s.  co m
        // Crea el cliente para realizar la conexion
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // Crea el mtodo con el que va a realizar la operacion
        HttpDelete delete = new HttpDelete(url);
        // Aade las cabeceras al metodo
        delete.addHeader("accept", "application/json; charset=UTF-8");
        delete.addHeader("Content-type", "application/json; charset=UTF-8");
        // Invocamos el servicio rest y obtenemos la respuesta
        HttpResponse response = httpClient.execute(delete);
        String status = response.getStatusLine().toString();

        // Comprobamos si ha fallado
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        } else {
            System.out.println("Se ha eliminado la cliente correctamente.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fpmislata.clientecategoriasjson.ClienteTest.java

private static void deleteCategoria(String url) {
    try {// w  w  w. ja va 2 s .  c  o m
        // Crea el cliente para realizar la conexion
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // Crea el mtodo con el que va a realizar la operacion
        HttpDelete delete = new HttpDelete(url);
        // Aade las cabeceras al metodo
        delete.addHeader("accept", "application/json; charset=UTF-8");
        delete.addHeader("Content-type", "application/json; charset=UTF-8");
        // Invocamos el servicio rest y obtenemos la respuesta
        HttpResponse response = httpClient.execute(delete);
        String status = response.getStatusLine().toString();

        // Comprobamos si ha fallado
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        } else {
            System.out.println("Se ha eliminado la categoria correctamente.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.drill.test.framework.Utils.java

/**
 * Posts/updates drill storage plugin content
 * //from w  ww . j av a2 s  .  co m
 * @param content
 *          string containing drill storage plugin
 * @param ipAddress
 *          IP address of node to update storage plugin for
 * @param pluginType
 *          type of plugin; e.g.: "dfs", "cp"
 * @return true if operation is successful
 * @throws Exception
 */
public static boolean postDrillStoragePlugin(String content, String ipAddress, String pluginType)
        throws IOException {
    StringBuilder builder = new StringBuilder();
    builder.append("http://" + ipAddress + ":8047/storage/" + pluginType);
    HttpPost post = new HttpPost(builder.toString() + ".json");
    post.setHeader("Content-Type", "application/json");
    post.setEntity(new StringEntity(content));
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    return isResponseSuccessful(response);
}

From source file:es.deustotech.piramide.utils.tts.TextToSpeechWeb.java

private static synchronized void speech(final Context context, final String text, final String language) {
    executor.submit(new Runnable() {
        @Override/* ww w .  j a  v  a  2 s .co m*/
        public void run() {
            try {
                final String encodedUrl = Constants.URL + language + "&q="
                        + URLEncoder.encode(text, Encoding.UTF_8.name());
                final DefaultHttpClient client = new DefaultHttpClient();
                HttpParams params = new BasicHttpParams();
                params.setParameter("http.protocol.content-charset", "UTF-8");
                client.setParams(params);
                final FileOutputStream fos = context.openFileOutput(Constants.MP3_FILE,
                        Context.MODE_WORLD_READABLE);
                try {
                    try {
                        final HttpResponse response = client.execute(new HttpGet(encodedUrl));
                        downloadFile(response, fos);
                    } finally {
                        fos.close();
                    }
                    final String filePath = context.getFilesDir().getAbsolutePath() + "/" + Constants.MP3_FILE;
                    final MediaPlayer player = MediaPlayer.create(context.getApplicationContext(),
                            Uri.fromFile(new File(filePath)));
                    player.start();
                    Thread.sleep(player.getDuration());
                    while (player.isPlaying()) {
                        Thread.sleep(100);
                    }
                    player.stop();

                } finally {
                    context.deleteFile(Constants.MP3_FILE);
                }
            } catch (InterruptedException ie) {
                // ok
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:uf.edu.AddLocation.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
    JSONObject obj = null;//from   ww  w . ja v  a2s.  com
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");

        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            String s = "{" + resultString;//+"}";
            Log.i(TAG, "Location String Received ");
            obj = (JSONObject) new JSONTokener(s).nextValue();
        } else {
            Log.i(TAG, "AddLocation: error response from the location server :" + response.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;//jsonObjRecv;
}

From source file:com.ilearnrw.reader.utils.HttpHelper.java

public static HttpResponse post(String url, String data) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = null;/*  w w  w .j a v a  2 s . com*/

    //HttpConnectionParams.setSoTimeout(client.getParams(), 25000);

    HttpPost post = new HttpPost(url);
    post.setHeader("Accept", "application/json");
    post.setHeader("Authorization", "Basic " + authString);
    post.setHeader("Content-Type", "application/json;charset=utf-8");

    try {
        post.setEntity(new StringEntity(data, HTTP.UTF_8));
        response = client.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return response;
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpRollupHandlerIntegrationTest.java

public static void testHappyCaseMultiFetchHTTPRequest(List<Locator> locators, String tenantId,
        DefaultHttpClient client) throws Exception {
    HttpPost post = new HttpPost(getBatchMetricsQueryURI(tenantId));
    JSONArray metricsToGet = new JSONArray();
    for (Locator locator : locators) {
        metricsToGet.add(locator.toString());
    }//  ww w  .  ja  v  a 2 s  .  c  om
    HttpEntity entity = new StringEntity(metricsToGet.toString(), ContentType.APPLICATION_JSON);
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}