Example usage for org.apache.http.params HttpProtocolParams setContentCharset

List of usage examples for org.apache.http.params HttpProtocolParams setContentCharset

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setContentCharset.

Prototype

public static void setContentCharset(HttpParams httpParams, String str) 

Source Link

Usage

From source file:com.rakesh.d4ty.YTDownloadThread.java

boolean downloadone(String sURL) {
    boolean rc = false;
    boolean rc204 = false;
    boolean rc302 = false;

    this.iRecursionCount++;

    // stop recursion
    try {//from w w w  .ja  v  a2  s.  c om
        if (sURL.equals(""))
            return (false);
    } catch (NullPointerException npe) {
        return (false);
    }
    if (JFCMainClient.getbQuitrequested())
        return (false); // try to get information about application shutdown

    debugoutput("start.");

    // TODO GUI option for proxy?
    // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
    // using local squid to save download time for tests

    try {
        // determine http_proxy environment variable
        if (!this.getProxy().equals("")) {

            String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", "");
            this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""),
                    Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http");

            SchemeRegistry supportedSchemes = new SchemeRegistry();
            supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUseExpectContinue(params, true);

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

            // with proxy
            this.httpclient = new DefaultHttpClient(ccm, params);
            this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy);
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        } else {
            // without proxy
            this.httpclient = new DefaultHttpClient();
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        }
        this.httpget = new HttpGet(getURI(sURL));
        if (sURL.toLowerCase().startsWith("https"))
            this.target = new HttpHost(getHost(sURL), 443, "https");
        else
            this.target = new HttpHost(getHost(sURL), 80, "http");
    } catch (Exception e) {
        debugoutput(e.getMessage());
    }

    debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString()));
    debugoutput("uri: ".concat(this.httpget.getURI().toString()));
    debugoutput("host: ".concat(this.target.getHostName()));
    debugoutput("using proxy: ".concat(this.getProxy()));

    // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work)
    /*
    this.localContext = new BasicHttpContext();
    if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context)
    ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient
    */

    // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again?

    try {
        this.response = this.httpclient.execute(this.target, this.httpget, this.localContext);
    } catch (ClientProtocolException cpe) {
        debugoutput(cpe.getMessage());
    } catch (UnknownHostException uhe) {
        output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ")
                .concat(uhe.getMessage()));
        debugoutput(uhe.getMessage());
    } catch (IOException ioe) {
        debugoutput(ioe.getMessage());
    } catch (IllegalStateException ise) {
        debugoutput(ise.getMessage());
    }

    /*
    CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN);
    CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC);
    CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ;
    try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( )));
    } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute
    try {
       debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString()));
       debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString()));
       debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString()));
    } catch (NullPointerException npe) {
    }
    */

    try {
        debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString()));
        //for (int i = 0; i < response.getAllHeaders().length; i++) {
        //   debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue()));
        //}

        // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
        if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)"))
                & !(rc204 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)204(.*)"))
                & !(rc302 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)302(.*)"))) {
            debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL));
            output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\""));
            return (rc & rc204 & rc302);
        }
        if (rc204) {
            debugoutput("last response code==204 - download: ".concat(this.sNextVideoURL.get(0)));
            rc = downloadone(this.sNextVideoURL.get(0));
            return (rc);
        }
        if (rc302)
            debugoutput(
                    "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));

    } catch (NullPointerException npe) {
        // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
        // response.getStatusLine() == null
        this.sVideoURL = null;
    }

    HttpEntity entity = null;
    try {
        entity = this.response.getEntity();
    } catch (NullPointerException npe) {
    }

    // try to read HTTP response body
    if (entity != null) {
        try {
            if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)"))
                this.textreader = new BufferedReader(new InputStreamReader(entity.getContent()));
            else
                this.binaryreader = new BufferedInputStream(entity.getContent());
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            // test if we got a webpage
            this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            if (this.sContentType.matches("^text/html(.*)")) {
                savetextdata();
                // test if we got the binary content
            } else if (this.sContentType.matches("video/(.)*")) {
                if (JFCMainClient.getbNODOWNLOAD())
                    reportheaderinfo();
                else
                    savebinarydata();
            } else { // content-type is not video/
                rc = false;
                this.sVideoURL = null;
            }
        } catch (IOException ex) {
            try {
                throw ex;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (RuntimeException ex) {
            try {
                throw ex;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } //if (entity != null)

    this.httpclient.getConnectionManager().shutdown();

    debugoutput("done: ".concat(sURL));
    try {
        if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) {
            debugoutput("cannot download video - URL does not seem to be valid: ".concat(this.sVideoURL));
            output(JFCMainClient.isgerman() ? "es gab ein Problem die Video URL zu finden!"
                    : "there was a problem getting the video URL!"); // deutsch
            output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!"
                    : "consider reporting the URL to author! - ").concat(this.sURL));
            rc = false;
        } else {
            debugoutput("try to download video from URL: ".concat(this.sVideoURL));
            rc = downloadone(this.sVideoURL);
        }
        this.sVideoURL = null;

    } catch (NullPointerException npe) {
    }

    return (rc);

}

From source file:com.skywomantech.app.symptommanagement.client.oauth.unsafe.EasyHttpClient.java

/**
 * Function that creates a ClientConnectionManager which can handle http and https. 
 * In case of https self signed or invalid certificates will be accepted.
 *//* w w  w .  ja v  a  2 s .  c  o  m*/
@SuppressWarnings("deprecation")
@Override
protected ClientConnectionManager createClientConnectionManager() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT));
    registry.register(new Scheme("https", new EasySSLSocketFactory(), HTTPS_PORT));

    return new ThreadSafeClientConnManager(params, registry);
}

From source file:com.manning.androidhacks.hack023.net.HttpHelper.java

private static void setConnectionParams(HttpParams httpParams) {
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
    HttpConnectionParams.setConnectionTimeout(httpParams, CONN_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CONN_TIMEOUT);
}

From source file:org.quickconnectfamily.sync.SynchronizedDB.java

/**
 * Creates a SynchronizedDB object used to interact with a local database and a remote HTTP service.  It 
 * sends a login request to the //w  ww . j a  va2 s . c om
 * @param theActivityRef - the activity that the database is associated with.  This is usually your initial Acivity class.
 * @param aDbName - the name of the SQLite file to be kept in sync.
 * @param aRemoteURL - the URL of the service that will respond to synchronization requests including the port number if not port 80.  
 * For security reasons it is suggested that your URL be an HTTPS URL but this is not required.
 * @param port - the port number of the remote HTTP service.
 * @param aRemoteUname - a security credential used in the remote service
 * @param aRemotePword - a security credential used in the remote service
 * @param syncTimeout - the amount of time in seconds to attempt all sync requests before timing out.
 * @throws DataAccessException
 * @throws URISyntaxException
 * @throws InterruptedException
 */
public SynchronizedDB(WeakReference<Context> theActivityRef, String aDbName, URL aRemoteURL, int port,
        String aRemoteUname, String aRemotePword, long syncTimeout)
        throws DataAccessException, URISyntaxException, InterruptedException {
    dbName = aDbName;
    remoteURL = aRemoteURL.toURI();
    remoteUname = aRemoteUname;
    remotePword = aRemotePword;
    this.theActivityRef = theActivityRef;

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (aRemoteURL.toExternalForm().indexOf("http") == 0) {
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
    } else if (aRemoteURL.toExternalForm().indexOf("https") == 0) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), port));
    }
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpClient = new DefaultHttpClient(cm, params);

    startTransaction();
    String errorMessage = null;
    //insert the required tables if they don't exist
    try {
        DataAccessResult aResult = DataAccessObject.transact(theActivityRef, aDbName,
                "CREATE TABLE IF NOT EXISTS sync_info(int id PRIMARY KEY  NOT NULL, last_sync TIMESTAMP);",
                null);
        if (aResult.getErrorDescription().equals("not an error")) {
            aResult = DataAccessObject.transact(theActivityRef, aDbName,
                    "CREATE TABLE IF NOT EXISTS sync_values(timeStamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, sql_key TEXT, sql_params TEXT)",
                    null);
            if (!aResult.getErrorDescription().equals("not an error")) {
                allTransactionStatementsExecuted = false;
                errorMessage = aResult.getErrorDescription();
            }
        } else {
            allTransactionStatementsExecuted = false;
            errorMessage = aResult.getErrorDescription();
        }
    } catch (DataAccessException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
        allTransactionStatementsExecuted = false;
        errorMessage = e.getLocalizedMessage();
    }
    endTransaction();
    if (allTransactionStatementsExecuted == false) {
        throw new DataAccessException("Error: Transaction failure. " + errorMessage);
    }

    /*
     * Do login and store context
     */
    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

}

From source file:com.mnxfst.testing.activities.http.TestHTTPRequestActivity.java

public void testExecuteHTTPRequest() throws HttpException, IOException {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, false);

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("www.heise.de", 80);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*from  www.  j  a  va2 s.c  o  m*/

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }

}

From source file:org.dasein.cloud.terremark.TerremarkMethod.java

public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")");
    }//from   w  ww .j a va2  s  .  c o m
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Talking to server at " + url);
        }

        if (parameters != null) {
            URIBuilder uri = null;
            try {
                uri = new URIBuilder(url);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            for (NameValuePair parameter : parameters) {
                uri.addParameter(parameter.getName(), parameter.getValue());
            }
            url = uri.toString();
        }

        HttpUriRequest method = null;
        if (methodType.equals(HttpMethodName.GET)) {
            method = new HttpGet(url);
        } else if (methodType.equals(HttpMethodName.POST)) {
            method = new HttpPost(url);
        } else if (methodType.equals(HttpMethodName.DELETE)) {
            method = new HttpDelete(url);
        } else if (methodType.equals(HttpMethodName.PUT)) {
            method = new HttpPut(url);
        } else if (methodType.equals(HttpMethodName.HEAD)) {
            method = new HttpHead(url);
        } else {
            method = new HttpGet(url);
        }
        HttpResponse status = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpParams params = new BasicHttpParams();

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

            attempts++;

            String proxyHost = provider.getProxyHost();
            if (proxyHost != null) {
                int proxyPort = provider.getProxyPort();
                boolean ssl = url.startsWith("https");
                params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                        new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http"));
            }
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                method.addHeader(entry.getKey(), entry.getValue());
            }
            if (body != null && body != ""
                    && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) {
                try {
                    HttpEntity entity = new StringEntity(body, "UTF-8");
                    ((HttpEntityEnclosingRequestBase) method).setEntity(entity);
                } catch (UnsupportedEncodingException e) {
                    logger.warn(e);
                }
            }
            if (wire.isDebugEnabled()) {

                wire.debug(methodType.name() + " " + method.getURI());
                for (Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                if (body != null) {
                    wire.debug(body);
                }
            }
            try {
                status = client.execute(method);
                if (wire.isDebugEnabled()) {
                    wire.debug("HTTP STATUS: " + status);
                }
            } catch (IOException e) {
                logger.error("I/O error from server communications: " + e.getMessage());
                e.printStackTrace();
                throw new InternalException(e);
            }
            int statusCode = status.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                    || statusCode == HttpStatus.SC_ACCEPTED) {
                try {
                    InputStream input = status.getEntity().getContent();

                    try {
                        return parseResponse(input);
                    } finally {
                        input.close();
                    }
                } catch (IOException e) {
                    logger.error("Error parsing response from Teremark: " + e.getMessage());
                    e.printStackTrace();
                    throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage());
                }
            } else if (statusCode == HttpStatus.SC_NO_CONTENT) {
                logger.debug("Recieved no content in response. Creating an empty doc.");
                DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = null;
                try {
                    docBuilder = dbfac.newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                }
                return docBuilder.newDocument();
            } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
                String msg = "OperationNotAllowed ";
                try {
                    msg += parseResponseToString(status.getEntity().getContent());
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                wire.error(msg);
                throw new TerremarkException(statusCode, "OperationNotAllowed", msg);
            } else {
                String response = "Failed to parse response.";
                ParsedError parsedError = null;
                try {
                    response = parseResponseToString(status.getEntity().getContent());
                    parsedError = parseErrorResponse(response);
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Received " + status + " from " + url);
                }
                if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
                        || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    if (attempts >= 5) {
                        String msg;
                        wire.warn(response);
                        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                            msg = "Cloud service is currently unavailable.";
                        } else {
                            msg = "The cloud service encountered a server error while processing your request.";
                            try {
                                msg = msg + "Response from server was:\n" + response;
                            } catch (RuntimeException runException) {
                                logger.warn(runException);
                            } catch (Error error) {
                                logger.warn(error);
                            }
                        }
                        wire.error(response);
                        logger.error(msg);
                        if (parsedError != null) {
                            throw new TerremarkException(parsedError);
                        } else {
                            throw new CloudException("HTTP Status " + statusCode + msg);
                        }
                    } else {
                        try {
                            Thread.sleep(5000L);
                        } catch (InterruptedException e) {
                            /* ignore */ }
                        return invoke();
                    }
                }
                wire.error(response);
                if (parsedError != null) {
                    throw new TerremarkException(parsedError);
                } else {
                    String msg = "\nResponse from server was:\n" + response;
                    logger.error(msg);
                    throw new CloudException("HTTP Status " + statusCode + msg);
                }
            }
        } finally {
            try {
                if (status != null) {
                    EntityUtils.consume(status.getEntity());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()");
        }
    }
}

From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java

HttpClient http() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, IOException {
    if (client == null) {
        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());
        HttpConnectionParams.setSoTimeout(params, getSoTimeout());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);/*w  w  w.  j ava2 s  .c  o m*/

        SSLSocketFactory sf = new EasySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        /*
         * ClientConnectionManager mgr = new ThreadSafeClientConnManager(
         * params, registry);
         */

        ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(mgr, params);

        // gzip?
        defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }

        });

        defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {

            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Header ceheader = entity.getContentEncoding();
                    if (ceheader != null) {
                        HeaderElement[] codecs = ceheader.getElements();
                        for (int i = 0; i < codecs.length; i++) {
                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                return;
                            }
                        }
                    }
                }
            }

        });
        client = defaultHttpClient;
    }
    return client;
}

From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java

public HttpClient getNewHttpClient() {
    try {//from w  w  w.  jav  a2 s  . c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        int timeout = 10 * 1000;
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.zia.freshdocs.cmis.CMIS.java

public InputStream makeHttpRequest(boolean isPost, String path, String payLoad, String contentType) {
    try {// w w w  .  j a  v a  2  s  .  c o m
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);
        params.setParameter("http.connection.timeout", new Integer(TIMEOUT));

        // registers schemes for both http and https
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), _prefs.getPort()));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), _prefs.getPort()));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);

        String url = new URL(_prefs.isSSL() ? "https" : "http", _prefs.getHostname(), buildRelativeURI(path))
                .toString();
        HttpClient client = new DefaultHttpClient(manager, params);
        client.getParams();
        _networkStatus = NetworkStatus.OK;

        HttpRequestBase request = null;

        if (isPost) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(payLoad));
        } else {
            request = new HttpGet(url);
        }

        try {

            if (contentType != null) {
                request.setHeader("Content-type", contentType);
            }

            HttpResponse response = client.execute(request);
            StatusLine status = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            int statusCode = status.getStatusCode();

            if ((statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) && entity != null) {
                // Just return the whole chunk
                return entity.getContent();
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                _networkStatus = NetworkStatus.CREDENTIALS_ERROR;
            }
        } catch (Exception ex) {
            Log.e(CMIS.class.getName(), "Get method error", ex);
            _networkStatus = NetworkStatus.CONNECTION_ERROR;
        }
    } catch (Exception ex) {
        Log.e(CMIS.class.getName(), "Get method error", ex);
        _networkStatus = NetworkStatus.UNKNOWN_ERROR;
    }

    return null;
}