Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:com.fujitsu.dc.test.jersey.HttpClientFactory.java

/**
 * HTTPClient?.//w  w w.  j av  a 2s. com
 * @param type 
 * @param connectionTimeout ()0????
 * @return ???HttpClient
 */
public static HttpClient create(final String type, final int connectionTimeout) {
    if (TYPE_DEFAULT.equalsIgnoreCase(type)) {
        return new DefaultHttpClient();
    }

    SSLSocketFactory sf = null;
    try {
        if (TYPE_INSECURE.equalsIgnoreCase(type)) {
            sf = createInsecureSSLSocketFactory();
        }
    } catch (Exception e) {
        return null;
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORTHTTPS, sf));
    schemeRegistry.register(new Scheme("http", PORTHTTP, PlainSocketFactory.getSocketFactory()));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
    // ClientConnectionManager cm = new
    // ThreadSafeClientConnManager(schemeRegistry);
    HttpClient hc = new DefaultHttpClient(cm, params);

    HttpParams params2 = hc.getParams();
    int timeout = TIMEOUT;
    if (connectionTimeout != 0) {
        timeout = connectionTimeout;
    }
    HttpConnectionParams.setConnectionTimeout(params2, timeout); // ?
    HttpConnectionParams.setSoTimeout(params2, timeout); // ??
    return hc;
}

From source file:kontrol.HttpUtil.java

public static HttpClient getCookielessHttpClient(int timeout) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);

    return httpClient;
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Gets the./*from w w  w  . j  a  va  2  s. c  o m*/
 * 
 * @param url
 *            the url
 * @param cap
 *            the cap
 * @param downloadDir
 *            the download dir
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void get(String url, String cap, String downloadDir) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "download/" + cap;
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpGet get = new HttpGet(url);

    HttpResponse response = client.execute(get);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        final double filesize = ht.getContentLength();

        FileOutputStream out = new FileOutputStream(FileUtils.JoinPath(downloadDir, cap));
        OutputStreamProgress cout = new OutputStreamProgress(out, new ProgressListener() {

            @Override
            public void transfered(long bytes, float rate) {
                int percent = (int) ((bytes / filesize) * 100);
                String bar = ProgressUtils.progressBar("Download Progress: ", percent, rate);
                System.out.print("\r" + bar);
            }
        });

        ht.writeTo(cout);
        out.close();
        System.out.println();
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:com.wrapp.android.webimage.ImageDownloader.java

public static Date getServerTimestamp(final URL imageUrl) {
    Date expirationDate = new Date();

    try {//from  w  w  w. j a  v a 2s  . c  om
        final String imageUrlString = imageUrl.toString();
        if (imageUrlString == null || imageUrlString.length() == 0) {
            throw new Exception("Passed empty URL");
        }
        LogWrapper.logMessage("Requesting image '" + imageUrlString + "'");
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpParams httpParams = httpClient.getParams();
        httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
        final HttpHead httpHead = new HttpHead(imageUrlString);
        final HttpResponse response = httpClient.execute(httpHead);

        Header[] header = response.getHeaders("Expires");
        if (header != null && header.length > 0) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
            expirationDate = dateFormat.parse(header[0].getValue());
            LogWrapper
                    .logMessage("Image at " + imageUrl.toString() + " expires on " + expirationDate.toString());
        }
    } catch (Exception e) {
        LogWrapper.logException(e);
    }

    return expirationDate;
}

From source file:com.groupon.odo.tests.HttpUtils.java

public static String doProxyGet(String url, BasicNameValuePair[] data) throws Exception {
    String fullUrl = url;/*from  ww  w  . j a va  2s.c o m*/

    if (data != null) {
        if (data.length > 0) {
            fullUrl += "?";
        }

        for (BasicNameValuePair bnvp : data) {
            fullUrl += bnvp.getName() + "=" + uriEncode(bnvp.getValue()) + "&";
        }
    }

    HttpGet get = new HttpGet(fullUrl);
    int port = Utils.getSystemPort(Constants.SYS_HTTP_PORT);
    HttpHost proxy = new HttpHost("localhost", port);
    HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
    client.getParams().setParameter(org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY, proxy);
    HttpResponse response = client.execute(get);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String accumulator = "";
    String line = "";
    Boolean firstLine = true;
    while ((line = rd.readLine()) != null) {
        accumulator += line;
        if (!firstLine) {
            accumulator += "\n";
        } else {
            firstLine = false;
        }
    }
    return accumulator;
}

From source file:mobisocial.metrics.MusubiExceptionHandler.java

static final HttpClient getHttpClient(Context context) {
    HttpClient http = new CertifiedHttpClient(context);
    HttpParams params = http.getParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 6000);
    HttpConnectionParams.setSoTimeout(params, 6000);
    return http;/*from   w w  w. j  a  v  a2  s. c o m*/
}

From source file:com.cloudhopper.sxmp.SxmpSender.java

static public Response send(String url, Request request, boolean shouldParseResponse)
        throws UnsupportedEncodingException, SxmpErrorException, IOException, SxmpParsingException,
        SAXException, ParserConfigurationException {
    // convert request into xml
    String requestXml = SxmpWriter.createString(request);
    String responseXml = null;/*from  www.ja va 2 s . c om*/

    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    long start = System.currentTimeMillis();
    long stop = 0;

    logger.debug("Request XML:\n" + requestXml);

    // execute request
    try {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(requestXml);
        // write old or new encoding?
        if (request.getVersion().equals(SxmpParser.VERSION_1_1)) {
            // v1.1 is utf-8
            entity.setContentType("text/xml; charset=\"utf-8\"");
        } else {
            // v1.0 was 8859-1, though that's technically wrong
            // unspecified XML must be encoded in UTF-8
            // maintained this way for backward compatibility
            entity.setContentType("text/xml; charset=\"iso-8859-1\"");
        }
        post.setEntity(entity);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // execute request (will throw exception if fails)
        responseXml = client.execute(post, responseHandler);

        stop = System.currentTimeMillis();
    } finally {
        // clean up all resources
        client.getConnectionManager().shutdown();
    }

    logger.debug("Response XML:\n" + responseXml);
    logger.debug("Response Time: " + (stop - start) + " ms");

    // deliver responses sometimes aren't parseable since its acceptable
    // for delivery responses to merely return "OK" and an HTTP 200 error
    if (!shouldParseResponse) {
        return null;
    } else {
        // convert response xml into an object
        SxmpParser parser = new SxmpParser(SxmpParser.VERSION_1_0);
        // v1.0 data remains in ISO-8859-1, and responses are v1.0
        ByteArrayInputStream bais = new ByteArrayInputStream(responseXml.getBytes("ISO-8859-1"));
        Operation op = parser.parse(bais);

        if (!(op instanceof Response)) {
            throw new SxmpErrorException(SxmpErrorCode.OPTYPE_MISMATCH,
                    "Unexpected response class type parsed");
        }

        return (Response) op;
    }
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Put./*from   w w  w .ja v  a 2  s. co m*/
 * 
 * @param filepath
 *            the filepath
 * @param url
 *            the url
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void put(String filepath, String url) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filepath);
    final double filesize = file.length();

    ContentBody fbody = new FileBodyProgress(file, new ProgressListener() {

        @Override
        public void transfered(long bytes, float rate) {
            int percent = (int) ((bytes / filesize) * 100);
            String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate);
            System.err.print("\r" + bar);
            if (percent == 100) {
                System.err.println();
                System.err.println("wait the gateway is processing and saving your file");
            }
        }
    });

    entity.addPart("File", fbody);

    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        String json = EntityUtils.toString(ht);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj = (JSONObject) parser.parse(json);
            System.out.println(obj.get("cap"));
        } catch (ParseException e) {
            System.err.println("Error during parsing the response: " + e.getMessage());
            System.exit(-1);
        }
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:com.appdynamics.openstack.nova.RestClient.java

static HttpClient httpClientWithTrustManager() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);

    httpClient.getParams().setParameter("http.connection-manager.max-per-host", 1);

    X509TrustManager tm = new X509TrustManager() {

        @Override//from   w  ww . jav  a  2  s. co m
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }
    };

    SSLContext ctx = SSLContext.getInstance("TLS");

    ctx.init(null, new TrustManager[] { tm }, null);

    SSLSocketFactory ssf = new SSLSocketFactory(ctx);

    ClientConnectionManager ccm = httpClient.getConnectionManager();

    SchemeRegistry sr = ccm.getSchemeRegistry();

    sr.register(new Scheme("https", ssf, 443)); // Scheme("https", ssf, 443));

    return new DefaultHttpClient(ccm, httpClient.getParams());

}

From source file:com.wrapp.android.webimage.ImageDownloader.java

public static boolean loadImage(final String imageKey, final URL imageUrl) {
    HttpEntity responseEntity = null;//from  ww  w . j  a  va 2 s  . co  m
    InputStream contentInputStream = null;

    try {
        final String imageUrlString = imageUrl.toString();
        if (imageUrlString == null || imageUrlString.length() == 0) {
            throw new Exception("Passed empty URL");
        }
        LogWrapper.logMessage("Requesting image '" + imageUrlString + "'");
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpParams httpParams = httpClient.getParams();
        httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
        final HttpGet httpGet = new HttpGet(imageUrlString);
        final HttpResponse response = httpClient.execute(httpGet);

        responseEntity = response.getEntity();
        if (responseEntity == null) {
            throw new Exception("No response entity for image: " + imageUrl.toString());
        }
        contentInputStream = responseEntity.getContent();
        if (contentInputStream == null) {
            throw new Exception("No content stream for image: " + imageUrl.toString());
        }

        Bitmap bitmap = BitmapFactory.decodeStream(contentInputStream);
        ImageCache.saveImageInFileCache(imageKey, bitmap);
        LogWrapper.logMessage("Downloaded image: " + imageUrl.toString());
        bitmap.recycle();
    } catch (IOException e) {
        LogWrapper.logException(e);
        return false;
    } catch (Exception e) {
        LogWrapper.logException(e);
        return false;
    } finally {
        try {
            if (contentInputStream != null) {
                contentInputStream.close();
            }
            if (responseEntity != null) {
                responseEntity.consumeContent();
            }
        } catch (IOException e) {
            LogWrapper.logException(e);
        }
    }

    return true;
}