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

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

Introduction

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

Prototype

public synchronized void setParams(final HttpParams params) 

Source Link

Document

Replaces the parameters.

Usage

From source file:es.deustotech.piramide.utils.net.RestClient.java

public static HttpEntity connect(String url, HttpEntity httpEntity) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.content-charset", "UTF-8");
    httpClient.setParams(params);
    final HttpGet httpGet = new HttpGet(url); //request object
    HttpResponse response = null;//from w ww.  j ava2s. co  m

    try {
        response = httpClient.execute(httpGet);
    } catch (ClientProtocolException cpe) {
        Log.d(Constants.TAG, cpe.getMessage());
    } catch (IOException ioe) {
        Log.d(Constants.TAG, ioe.getMessage());
    }
    return httpEntity = response.getEntity();
}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Downloads a file from the Internet//from   w w  w .  jav a  2  s. c om
 * @param address The URL of the file
 * @param dest The destination directory
 * @return The queried file
 * @throws IOException HTTP connection error, or writing error
 */
public static File download(URL address, File dest) throws IOException {
    File result = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    //Open streams
    try {
        HttpGet httpGet = new HttpGet(address.toExternalForm());
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 4000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);

        //Launch streams for download
        in = new BufferedInputStream(response.getEntity().getContent());
        String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1);
        File tmp = new File(dest.getPath() + File.separator + filename);
        out = new BufferedOutputStream(new FileOutputStream(tmp));

        //Test if connection is OK
        if (response.getStatusLine().getStatusCode() / 100 == 2) {
            //Download and write
            try {
                int byteRead = in.read();
                while (byteRead >= 0) {
                    out.write(byteRead);
                    byteRead = in.read();
                }
                result = tmp;
            } catch (IOException e) {
                throw new IOException("Error while writing file: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error while downloading: " + e.getMessage());
    } finally {
        //Close streams
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
    return result;
}

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  2s.  c  o 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:com.onemorecastle.util.HttpFetch.java

public static Bitmap fetchBitmap(String imageAddress, int sampleSize)
        throws MalformedURLException, IOException {
    Bitmap bitmap = null;/*w  w  w . j  a v  a2s . c o  m*/
    DefaultHttpClient httpclient = null;
    try {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        HttpConnectionParams.setSocketBufferSize(httpParameters, 512);
        HttpGet httpRequest = new HttpGet(URI.create(imageAddress));
        httpclient = new DefaultHttpClient();
        httpclient.setParams(httpParameters);
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
        InputStream instream = bufHttpEntity.getContent();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //first decode with inJustDecodeBounds=true to check dimensions
        options.inJustDecodeBounds = true;
        options.inSampleSize = sampleSize;
        BitmapFactory.decodeStream(instream, null, options);
        //decode bitmap with inSampleSize set
        options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inDither = true;
        options.inJustDecodeBounds = false;
        //response=(HttpResponse)httpclient.execute(httpRequest);
        //entity=response.getEntity();
        //bufHttpEntity=new BufferedHttpEntity(entity);
        instream = bufHttpEntity.getContent();
        bitmap = BitmapFactory.decodeStream(instream, null, options);
        //close out stuff
        try {
            instream.close();
            bufHttpEntity.consumeContent();
            entity.consumeContent();
        } finally {
            instream = null;
            bufHttpEntity = null;
            entity = null;
        }
    } catch (Exception x) {
        Log.e("HttpFetch.fetchBitmap", imageAddress, x);
    } finally {
        httpclient = null;
    }
    return (bitmap);
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpGetCommand(String url) throws Exception {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;//ww w.  ja v a 2 s . c o  m
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpGet getRequest = new HttpGet(url);
        getRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(getRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute GET URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute GET URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("GET URL API: {} returns: {}", url, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpPutCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;/*  w w  w.ja  va2  s .  co m*/
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpPut putRequest = new HttpPut(url);
        putRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        putRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(putRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute PUT URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute PUT URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("PUT URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpPostCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;/*from ww w.  ja  va 2  s .c  o m*/
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpPost postRequest = new HttpPost(url);
        if (StringUtils.isNotEmpty(jsonBody))
            postRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        postRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(postRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute POST URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute POST URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("POST URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}

From source file:org.openqa.selenium.remote.internal.HttpClientFactory.java

public HttpClient getGridHttpClient(int connection_timeout, int socket_timeout) {
    DefaultHttpClient gridClient = new DefaultHttpClient(gridClientConnectionManager);
    gridClient.setRedirectStrategy(new MyRedirectHandler());
    gridClient.setParams(getGridHttpParams(connection_timeout, socket_timeout));
    gridClient.setRoutePlanner(getRoutePlanner(gridClient.getConnectionManager().getSchemeRegistry()));
    gridClient.getConnectionManager().closeIdleConnections(100, TimeUnit.MILLISECONDS);

    return gridClient;
}

From source file:gtfsrt.provider.util.GtfsrtProviderImpl.java

/**
 * This method read the GTFS-RT feed available on the TriMet website,
 * and create another GTFS-RT feed with some modified trip updates.
 *//*  ww  w .j ava  2 s  .  c om*/
private void refreshGTFSRealtime() throws IOException {

    /* The FeedMessage.Builder is what we will use to build up our GTFS-RT feed */
    FeedMessage.Builder tripUpdates = GtfsRealtimeLibrary.createFeedMessageBuilder();

    try {

        /* Read the TriMet GTFS-RT feed */
        HttpGet httpget = new HttpGet(
                "http://developer.trimet.org/ws/V1/TripUpdate/appID/C725DEA31C7A28B860DC29BBA");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.setParams(httpParams);
        HttpResponse response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() != 200)
            return;
        HttpEntity entity = response.getEntity();
        if (entity == null)
            return;

        InputStream is = entity.getContent();
        if (is != null) {
            // Decode message
            FeedMessage feedMessage = FeedMessage.parseFrom(is);
            List<FeedEntity> feedEntityList = feedMessage.getEntityList();

            // Header
            tripUpdates.setHeader(feedMessage.getHeader());

            for (FeedEntity feedEntity : feedEntityList) {
                if (feedEntity.hasTripUpdate()) {
                    TripUpdate update = feedEntity.getTripUpdate();

                    TripDescriptor trip = update.getTrip();

                    /* Deleting trip updates already contained in the original feed */
                    if (trips.containsKey(trip.getTripId()))
                        continue;

                    /**
                     * Create a new feed entity to wrap the trip update and add it to the
                     * GTFS-realtime trip updates feed.
                     */
                    FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder();
                    tripUpdateEntity.setId(feedEntity.getId());
                    tripUpdateEntity.setTripUpdate(update);

                    tripUpdates.addEntity(tripUpdateEntity);
                }
            }

            Trip t;
            TripDescriptor.Builder tripDescriptor;
            TripUpdate.Builder tripUpdate;
            FeedEntity.Builder tripUpdateEntity;
            for (String s : trips.keySet()) {
                t = trips.get(s);
                tripDescriptor = TripDescriptor.newBuilder();
                tripDescriptor.setTripId(s);
                tripUpdate = addDelayForTrip(tripDescriptor, t.getDelay(), t.getNb_sequences()); // update.getStopTimeUpdateCount()) ;
                tripUpdateEntity = FeedEntity.newBuilder();
                tripUpdateEntity.setId(tripDescriptor.getTripId());
                tripUpdateEntity.setTripUpdate(tripUpdate);
                tripUpdates.addEntity(tripUpdateEntity);
            }

        }
    } catch (Exception e) {
        System.err.println("Error while loading GTFS RT feed");
    }

    /* Build out the final GTFS-realtime feed messages and save them */
    _gtfsRealtimeProvider.setTripUpdates(tripUpdates.build());

}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java

@Override
protected HttpClient client() {
    final DefaultHttpClient client = (DefaultHttpClient) super.client();

    // always configure with current proxy and params... settings may have changed
    client.setParams(createHttpParams(config.getGlobalRemoteStorageContext()));
    configureProxy(client, config.getGlobalRemoteStorageContext());

    return client;
}