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

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

Introduction

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

Prototype

public synchronized void setCookieStore(final CookieStore cookieStore) 

Source Link

Usage

From source file:net.vexelon.mobileops.GLBClient.java

/**
 * Initialize Http Client/*from  w ww  .ja v a  2s. c  o m*/
 */
private void initHttpClient() {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgentHelper.getRandomUserAgent());
    //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    // Bugfix #1: The target server failed to respond
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    DefaultHttpClient client = new DefaultHttpClient(params);

    httpCookieStore = new BasicCookieStore();
    client.setCookieStore(httpCookieStore);

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, httpCookieStore);

    // Bugfix #1: Adding retry handler to repeat failed requests
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

            if (executionCount >= MAX_REQUEST_RETRIES) {
                return false;
            }

            if (exception instanceof NoHttpResponseException || exception instanceof ClientProtocolException) {
                return true;
            }

            return false;
        }
    };
    client.setHttpRequestRetryHandler(retryHandler);

    // SSL
    HostnameVerifier verifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    try {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", new PlainSocketFactory(), 80));
        registry.register(new Scheme("https", new TrustAllSocketFactory(), 443));

        SingleClientConnManager connMgr = new SingleClientConnManager(client.getParams(), registry);

        httpClient = new DefaultHttpClient(connMgr, client.getParams());
    } catch (InvalidAlgorithmParameterException e) {
        //         Log.e(Defs.LOG_TAG, "", e);

        // init without connection manager
        httpClient = new DefaultHttpClient(client.getParams());
    }

    HttpsURLConnection.setDefaultHostnameVerifier(verifier);

}

From source file:sand.actionhandler.weibo.UdaClient.java

public static String syn(String url) {
    String content = "";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from w w  w  . j  a  v  a  2 s.  c  o m*/
        httpclient = createHttpClient();

        HttpGet httpget = new HttpGet(url);

        // Execute HTTP request
        //System.out.println("executing request " + httpget.getURI());
        //logger.info("executing request " + httpget.getURI());

        //            System.out.println("----------------------------------------");
        //            System.out.println(response.getStatusLine());
        //            System.out.println(response.getLastHeader("Content-Encoding"));
        //            System.out.println(response.getLastHeader("Content-Length"));
        //            System.out.println("----------------------------------------");

        //System.out.println(entity.getContentType());

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        CookieStore cookieStore = new BasicCookieStore();

        addCookie(cookieStore);
        // 
        httpclient.setCookieStore(cookieStore);
        //httpclient.ex
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            content = EntityUtils.toString(entity);
            System.out.println(content);
            System.out.println("----------------------------------------");
            System.out.println("Uncompressed size: " + content.length());
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return content;
}

From source file:com.ibm.sbt.services.endpoints.FormEndpoint.java

public boolean login(String user, String password) throws AuthenticationException {
    boolean validAuthentication = false;
    String requestUrl = getUrl();
    setUser(user);//from   ww  w .  ja v  a2s .  c  om
    setPassword(password);

    try {
        if (!(getLoginFormUrl().startsWith("/"))) {
            requestUrl = requestUrl.concat("/");
        }
        requestUrl = requestUrl.concat(getLoginFormUrl());
        BasicCookieStore cookieStore = new BasicCookieStore();
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

        if (isForceTrustSSLCertificate()) {
            defaultHttpClient = SSLUtil.wrapHttpClient(defaultHttpClient); // Configure httpclient to accept all SSL certificates
        }
        if (isForceDisableExpectedContinue()) {
            defaultHttpClient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        }
        if (StringUtil.isNotEmpty(getHttpProxy())) {
            defaultHttpClient = ProxyDebugUtil.wrapHttpClient(defaultHttpClient, getHttpProxy()); // Configure httpclient to direct all traffic through proxy clients
        }

        defaultHttpClient.setCookieStore(cookieStore);
        HttpPost httpost = new HttpPost(requestUrl);
        List<NameValuePair> formParams = getLoginFormParameters(); // retrieve platform specific login parameters
        httpost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

        //getting to interface to avoid 
        //java.lang.NoSuchMethodError: org/apache/http/impl/client/DefaultHttpClient.execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHttpResponse;
        //when run from different version of HttpClient (that's why it is deprecated)
        HttpClient httpClient = defaultHttpClient;

        HttpResponse resp = httpClient.execute(httpost);
        int code = resp.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            validAuthentication = true;
        }
        List<Cookie> cookies = cookieStore.getCookies();
        setCookieCache(cookies);

    } catch (IOException e) {
        throw new AuthenticationException(e, "FormEndpoint failed to authenticate");
    }
    return validAuthentication;

}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected boolean prepareForwardingCookies(HttpRequestBase method, HttpServletRequest request,
        DefaultHttpClient httpClient) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    Cookie[] cookies = request.getCookies();
    BasicCookieStore cs = new BasicCookieStore();
    httpClient.setCookieStore(cs);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookiename = cookie.getName();
                if (StringUtil.isNotEmpty(cookiename)) {
                    String cookieval = cookie.getValue();
                    if (cookiename.startsWith(PASSTHRUID)) {
                        cookiename = cookiename.substring(PASSTHRUID.length());
                        if (isCookieAllowed(cookiename)) {
                            String[] parts = decodeCookieNameAndPath(cookiename);
                            if (parts != null && parts.length == 3) {
                                cookiename = parts[0];
                                String path = parts[1];
                                String domain = parts[2];

                                // Got stored domain now see if it matches destination
                                BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                                methodcookie.setDomain(domain);
                                methodcookie.setPath(path);
                                cs.addCookie(methodcookie);
                                if (getDebugHook() != null) {
                                    getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                            methodcookie.toString());
                                }//  w  w  w.ja v  a2s .c  o  m
                            }
                        }
                    } else if (isCookieAllowed(cookiename)) {
                        BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                        String domain = cookie.getDomain();
                        if (domain == null) {
                            try {
                                domain = method.getURI().getHost();
                                domain = domain.substring(domain.indexOf('.'));
                            } catch (Exception e) {
                                domain = "";
                            }
                        }
                        methodcookie.setDomain(domain);
                        String path = cookie.getPath();
                        if (path == null) {
                            path = "/";
                        }
                        methodcookie.setPath(path);
                        cs.addCookie(methodcookie);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                    methodcookie.toString());
                        }
                    }
                }
            }
        }
    }
    ProxyProfiler.profileTimedRequest(timedObject, "perpareForwardingCookie");
    return true;
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static void requery(String tableName, Class clazz, String key)
        throws ClientProtocolException, IOException, JSONException, Exception {
    Log.i(TAG, "Got key " + key + " but couldn't find related parent tr, requerying ...");
    String url = FLOWZR_API_URL + nsString + "/key/?tableName=" + DatabaseHelper.TRANSACTION_TABLE + "&key="
            + key;//from   w  ww.j  a va2  s .c o m
    StringBuilder builder = new StringBuilder();
    DefaultHttpClient http_client2 = new DefaultHttpClient();
    http_client2.setCookieStore(http_client.getCookieStore());
    HttpGet httpGet = new HttpGet(url);
    HttpResponse httpResponse = http_client2.execute(httpGet);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream content = httpEntity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    JSONObject o = new JSONObject(builder.toString()).getJSONArray(DatabaseHelper.TRANSACTION_TABLE)
            .getJSONObject(0);
    saveEntityFromJson(o, tableName, clazz, 1);
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * /*from ww  w. j a v a  2 s  . c o m*/
 * @param baseURL
 * @param parametersBody
 * @param sessionId
 * @param fileToUpload - The file to upload.
 * @param filename - The name of the file to use during the upload process.
 * @return The response received from the Minus API.
 * @throws MinusException
 */
public static MinusHttpResponse doUpload(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final File fileToUpload, final String filename) throws MinusException {

    DefaultHttpClient client = null;
    HttpPost uploadRequest = null;
    InputStream responseContent = null;

    try {
        String url = baseURL;
        if (parametersBody != null && !parametersBody.isEmpty()) {
            url += CommonUtils.encodeParams(parametersBody);
        }
        uploadRequest = new HttpPost(url);
        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        FileEntity fileEntity = new FileEntity(fileToUpload, "application/octet-stream");
        uploadRequest.setEntity(fileEntity);

        // We add this headers as specified by the Minus.com API during file
        // upload.
        uploadRequest.addHeader("Content-Disposition", "attachment; filename=a.bin");
        uploadRequest.addHeader("Content-Type", "application/octet-stream");

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpResponse httpResponse = client.execute(uploadRequest);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        StringBuilder result = new StringBuilder();
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity respEntity = httpResponse.getEntity();
            if (respEntity != null) {
                result.append(EntityUtils.toString(respEntity));
                EntityUtils.consume(respEntity);
            }

        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append(" Upload failed => ").append(httpResponse.getStatusLine());
            if (uploadRequest != null) {
                errMsg.append(" : ").append(uploadRequest.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result.toString(), sessionCookie);

    } catch (Exception e) {
        if (uploadRequest != null) {
            uploadRequest.abort();
        }
        String errMsg = "Error while uploading file (" + fileToUpload + ") : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:org.tellervo.desktop.wsi.WSIServerDetails.java

/**
 * Ping the server to update status/*from   www .j  a v a  2  s  . c o m*/
 * 
 * @return
 */
public boolean pingServer() {
    // First make sure we have a network connection
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nic = interfaces.nextElement();
            if (nic.isLoopback())
                continue;

            if (nic.isUp()) {
                log.debug("Network adapter '" + nic.getDisplayName() + "' is up");
                isNetworkConnected = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (!isNetworkConnected) {
        status = WSIServerStatus.NO_CONNECTION;
        errMessage = "You do not appear to have a network connection.\nPlease check you network and try again.";
        return false;
    }

    URI url = null;
    BufferedReader dis = null;
    DefaultHttpClient client = new DefaultHttpClient();

    try {

        String path = App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid-url!");

        url = new URI(path.trim());

        // Check we're accessing HTTP or HTTPS connection
        if (url.getScheme() == null
                || ((!url.getScheme().equals("http")) && !url.getScheme().equals("https"))) {
            errMessage = "The webservice URL is invalid.  It should begin http or https";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        }

        // load cookies
        client.setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore());

        if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) {
            // Using strict security so don't allow self signed certificates for SSL
        } else {
            // Not using strict security so allow self signed certificates for SSL
            if (url.getScheme().equals("https"))
                WebJaxbAccessor.setSelfSignableHTTPSScheme(client);
        }

        HttpGet req = new HttpGet(url);

        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpResponse response = client.execute(req);

        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream responseIS = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS));
            String s = "";
            while ((s = reader.readLine()) != null) {
                if (s.contains("<webserviceVersion>")) {
                    String[] strparts = s.split("<[/]*webserviceVersion>");
                    if (strparts.length > 0)
                        parserThisServerVersion(strparts[1]);

                    status = WSIServerStatus.VALID;
                    return true;
                } else if (s.startsWith("<b>Parse error</b>:")) {
                    status = WSIServerStatus.STATUS_ERROR;
                    errMessage = s.replace("<b>", "").replace("</b>", "").replace("<br />", "");
                    return false;
                }
            }
        } else if (response.getStatusLine().getStatusCode() == 403) {
            String serverType = "";
            try {
                serverType = "(" + response.getHeaders("Server")[0].getValue() + ")";
            } catch (Exception e) {
            }

            errMessage = "The webserver " + serverType
                    + " reports you do not have permission to access this URL.\n"
                    + "This is a problem with the server setup, not your Tellervo username/password.\n"
                    + "Contact your systems administrator for help.";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else if (response.getStatusLine().getStatusCode() == 404) {
            errMessage = "Server reports that there is no webservice at this URL.\nPlease check and try again.";
            log.debug(errMessage);
            status = WSIServerStatus.URL_NOT_TELLERVO_WS;
            return false;
        } else if (response.getStatusLine().getStatusCode() == 407) {
            errMessage = "Proxy authentication is required to access this server.\nCheck your proxy server settings and try again.";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else if (response.getStatusLine().getStatusCode() >= 500) {
            errMessage = "Internal server error (code " + response.getStatusLine().getStatusCode()
                    + ").\nContact your systems administrator";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else if (response.getStatusLine().getStatusCode() >= 300
                && response.getStatusLine().getStatusCode() < 400) {
            errMessage = "Server reports that your request has been redirected to a different URL.\nCheck your URL and try again.";
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        } else {
            errMessage = "The server is returning an error:\nCode: " + response.getStatusLine().getStatusCode()
                    + "\n" + response.getStatusLine().getReasonPhrase();
            log.debug(errMessage);
            status = WSIServerStatus.STATUS_ERROR;
            return false;
        }

    } catch (ClientProtocolException e) {
        errMessage = "There was as problem with the HTTP protocol.\nPlease contact the Tellervo developers.";
        log.debug(errMessage);
        status = WSIServerStatus.STATUS_ERROR;
        return false;
    } catch (SSLPeerUnverifiedException sslex) {
        errMessage = "You have strict security policy enabled but the server you are connecting to does not have a valid SSL certificate.";
        log.debug(errMessage);
        status = WSIServerStatus.SSL_CERTIFICATE_PROBLEM;
        return false;
    } catch (IOException e) {

        if (url.toString().startsWith("http://10.")) {
            // Provide extra help to those failing to access a local server address
            errMessage = "There is no response from the server at this URL. Are you sure this is the correct address?\n\nPlease note that the URL you have specified is a local network address. You will need to be on the same network as the server to gain access.";
        } else if (e.getMessage().contains("hostname in certificate didn't match")) {
            errMessage = "The security certificate for this server is for a different domain.  This could be an indication of a 'man-in-the-middle' attack.";
        } else {
            errMessage = "There is no response from the server at this URL.\nAre you sure this is the correct address and that\nthe server is turned on and configured correctly?";
        }
        log.debug(errMessage);
        log.debug("IOException " + e.getLocalizedMessage());
        status = WSIServerStatus.URL_NOT_RESPONDING;
        return false;
    } catch (URISyntaxException e) {
        errMessage = "The web service URL you entered was malformed.\nPlease check for typos and try again.";
        log.debug(errMessage);
        status = WSIServerStatus.MALFORMED_URL;
        return false;
    } catch (IllegalStateException e) {
        errMessage = "This communications protocol is not supported.\nPlease contact your systems administrator.";
        log.debug(errMessage);
        status = WSIServerStatus.MALFORMED_URL;
        return false;
    } catch (Exception e) {
        errMessage = "The URL you specified exists, but does not appear to be a Tellervo webservice.\nPlease check and try again.";
        log.debug(errMessage);
        status = WSIServerStatus.URL_NOT_TELLERVO_WS;
        return false;
    } finally {
        try {
            if (dis != null) {
                dis.close();
            }
        } catch (IOException e) {
        }
    }

    status = WSIServerStatus.URL_NOT_TELLERVO_WS;

    return false;

}

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {//w w  w . ja v a 2  s  .com
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runDefault() throws IOException {
    Log.v("TwAjax", "runDefault URL=" + myUrl);

    // Create a new HttpClient and Get/Post Header
    DefaultHttpClient httpclient = getNewHttpClient();
    setHttpClientProxy(httpclient);//  w  w w .  j  ava2s  .c o m
    httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    //final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(httpclient.getParams(), false);

    HttpRequestBase m;
    if (myMethod == "POST") {
        m = new HttpPost(myUrl);
        ((HttpPost) m).setEntity(new UrlEncodedFormEntity(myPostData, "utf-8"));
    } else {
        m = new HttpGet(myUrl);
    }
    m.addHeader("Host", m.getURI().getHost());
    if (twSession != null)
        m.addHeader("Cookie", "twnetSID=" + twSession);
    httpclient.setCookieStore(cookieStoreManager);

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        m.addHeader("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    // Execute HTTP Get/Post Request
    HttpResponse response = httpclient.execute(m);
    //InputStream is = response.getEntity().getContent();
    myHttpStatus = response.getStatusLine().getStatusCode();
    if (this.fetchHeader != null) {
        this.fetchHeaderResult = response.getHeaders(this.fetchHeader);
        Header[] h = response.getAllHeaders();
        for (Header hh : h)
            Log.d(TAG, "Header " + hh.getName() + "=" + hh.getValue());

    } else if (this.downloadToFile != null) {
        Log.v("TwAjax", "runDefault downloadToFile=" + downloadToFile);
        // download the file
        InputStream input = new BufferedInputStream(response.getEntity().getContent());
        OutputStream output = new FileOutputStream(downloadToFile);

        byte data[] = new byte[1024];

        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            //publishProgress((int)(total*100/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } else if (this.convertToBitmap) {
        myBmpResult = BitmapFactory.decodeStream(response.getEntity().getContent());
    } else if (this.convertToXml) {
        try {
            myXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(response.getEntity().getContent());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }

    } else {
        myResult = EntityUtils.toString(response.getEntity(), "UTF-8");
    }
    //BufferedInputStream bis = new BufferedInputStream(is);
    //ByteArrayBuffer baf = new ByteArrayBuffer(50);

    //int current = 0;
    //while((current = bis.read()) != -1){
    //    baf.append((byte)current);
    //}

    //myResult = new String(baf.toByteArray(), "utf-8");
    success = true;
}

From source file:ti.modules.titanium.network.TiHTTPClient.java

protected DefaultHttpClient createClient() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 5);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(5);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry),
            params);/*from w  w w .  j a va2s . c o  m*/
    httpClient.setCookieStore(cookieStore);

    return httpClient;
}