Example usage for org.apache.http.impl.conn SingleClientConnManager SingleClientConnManager

List of usage examples for org.apache.http.impl.conn SingleClientConnManager SingleClientConnManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn SingleClientConnManager SingleClientConnManager.

Prototype

@Deprecated
public SingleClientConnManager(final HttpParams params, final SchemeRegistry schreg) 

Source Link

Document

Creates a new simple connection manager.

Usage

From source file:com.cssn.samplesdk.ShowDataActivity.java

private JSONObject sendJsonRequest(int port, String uri, JSONObject param)
        throws ClientProtocolException, IOException, JSONException {
    //HttpClient httpClient = new DefaultHttpClient();
    DefaultHttpClient client = new DefaultHttpClient();
    X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SchemeRegistry registry = new SchemeRegistry();

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpPost httpPost = new HttpPost(uri);
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    httpPost.addHeader("dataType", "json");

    if (param != null) {
        HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
        httpPost.setEntity(bodyEntity);//w ww  . ja  va 2  s  .c o  m
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        String result = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            result = sb.toString();
            instream.close();
        }

        httpPost.abort();
        return result != null ? new JSONObject(result) : null;
    } catch (Exception e1) {
        e1.printStackTrace();
        return null;
    }

}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public boolean login() {
    // System.out.println("--L--- LOGIN START -----");

    String login_url = "https://www.geocaching.com/login/default.aspx";

    DefaultHttpClient client2 = null;/*from www  .  j  av a 2  s.c o  m*/
    HttpHost proxy = null;

    if (CacheDownloader.DEBUG2_) {
        // NEVER enable this on a production release!!!!!!!!!!
        // NEVER enable this on a production release!!!!!!!!!!
        trust_Every_ssl_cert();

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

        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

        proxy = new HttpHost("192.168.0.1", 8888);
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
        client2 = new DefaultHttpClient(cm, params);
        // NEVER enable this on a production release!!!!!!!!!!
        // NEVER enable this on a production release!!!!!!!!!!
    } else {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        client2 = new DefaultHttpClient(httpParameters);
    }

    if (CacheDownloader.DEBUG2_) {
        client2.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    // read first page to check for login
    // read first page to check for login
    // read first page to check for login

    String websiteData2 = null;
    URI uri2 = null;
    try {
        uri2 = new URI(login_url);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return false;
    }

    client2.setCookieStore(cookie_jar);

    HttpGet method2 = new HttpGet(uri2);

    method2.addHeader("User-Agent",
            "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
    method2.addHeader("Pragma", "no-cache");
    method2.addHeader("Accept-Language", "en");

    HttpResponse res = null;
    try {
        res = client2.execute(method2);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
        return false;
    } catch (IOException e1) {
        e1.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    InputStream data = null;
    try {
        data = res.getEntity().getContent();
    } catch (IllegalStateException e1) {
        e1.printStackTrace();
        return false;
    } catch (IOException e1) {
        e1.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    websiteData2 = generateString(data);

    if (CacheDownloader.DEBUG_)
        System.out.println("111 cookies=" + dumpCookieStore(client2.getCookieStore()));
    cookie_jar = client2.getCookieStore();

    // on every page
    final Matcher matcherLogged2In = patternLogged2In.matcher(websiteData2);
    if (matcherLogged2In.find()) {
        if (CacheDownloader.DEBUG_)
            System.out.println("login: -> already logged in (1)");
        return true;
    }

    // after login
    final Matcher matcherLoggedIn = patternLoggedIn.matcher(websiteData2);
    if (matcherLoggedIn.find()) {
        if (CacheDownloader.DEBUG_)
            System.out.println("login: -> already logged in (2)");
        return true;
    }
    // read first page to check for login
    // read first page to check for login
    // read first page to check for login

    // ok post login data as formdata
    // ok post login data as formdata
    // ok post login data as formdata
    // ok post login data as formdata
    HttpPost method = new HttpPost(uri2);

    method.addHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0) Firefox/7.0");
    method.addHeader("Pragma", "no-cache");
    method.addHeader("Content-Type", "application/x-www-form-urlencoded");
    method.addHeader("Accept-Language", "en");

    List<NameValuePair> loginInfo = new ArrayList<NameValuePair>();

    loginInfo.add(new BasicNameValuePair("__EVENTTARGET", ""));
    loginInfo.add(new BasicNameValuePair("__EVENTARGUMENT", ""));

    String[] viewstates = getViewstates(websiteData2);
    if (CacheDownloader.DEBUG_)
        System.out.println("vs==" + viewstates[0]);
    putViewstates(loginInfo, viewstates);

    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$tbUsername",
            this.main_aagtl.global_settings.options_username));
    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$tbPassword",
            this.main_aagtl.global_settings.options_password));
    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$btnSignIn", "Login"));
    loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$cbRememberMe", "on"));

    //for (int i = 0; i < loginInfo.size(); i++)
    //{
    //   System.out.println("x*X " + loginInfo.get(i).getName() + " " + loginInfo.get(i).getValue());
    //}

    // set cookies
    client2.setCookieStore(cookie_jar);

    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(loginInfo, HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }

    //      try
    //      {
    //         System.out.println("1 " + entity.toString());
    //         InputStream in2 = entity.getContent();
    //         InputStreamReader ir2 = new InputStreamReader(in2, "utf-8");
    //         BufferedReader r = new BufferedReader(ir2);
    //         System.out.println("line=" + r.readLine());
    //      }
    //      catch (Exception e2)
    //      {
    //         e2.printStackTrace();
    //      }

    method.setEntity(entity);

    HttpResponse res2 = null;
    try {
        res2 = client2.execute(method);
        if (CacheDownloader.DEBUG_)
            System.out.println("login response ->" + String.valueOf(res2.getStatusLine()));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    //      for (int x = 0; x < res2.getAllHeaders().length; x++)
    //      {
    //         System.out.println("## n=" + res2.getAllHeaders()[x].getName());
    //         System.out.println("## v=" + res2.getAllHeaders()[x].getValue());
    //      }

    InputStream data2 = null;
    try {
        data2 = res2.getEntity().getContent();
    } catch (IllegalStateException e1) {
        e1.printStackTrace();
        return false;
    } catch (IOException e1) {
        e1.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    websiteData2 = generateString(data2);

    if (CacheDownloader.DEBUG_)
        System.out.println("2222 cookies=" + dumpCookieStore(client2.getCookieStore()));
    cookie_jar = client2.getCookieStore();

    String[] viewstates2 = getViewstates(websiteData2);
    if (CacheDownloader.DEBUG_)
        System.out.println("vs==" + viewstates2[0]);

    //      System.out.println("******");
    //      System.out.println("******");
    //      System.out.println("******");
    //      System.out.println(websiteData2);
    //      System.out.println("******");
    //      System.out.println("******");
    //      System.out.println("******");

    return true;

}

From source file:com.mwebster.exchange.SyncManager.java

static public synchronized ClientConnectionManager getClientConnectionManager(String accountUUID) {

    Log.d(TAG, "Requesting SSL factory for account UUID: " + accountUUID);
    if (accountUUID == null && validationKeyStore != null) {
        // Validating account, use temporarily provided keystore
        Log.d(TAG, "Create SSL factory with validation keystore");
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        try {/*  w  w  w  . j  av a 2  s .  c  o  m*/
            registry.register(new Scheme("https", new SSLSocketFactory(validationKeyStore, ""), 443));
        } catch (Exception e) {
            throw new Error(e);
        }
        // Use "insecure" socket factory.
        SSLSocketFactory sf = new SSLSocketFactory(SSLUtils.getSSLSocketFactory(true));
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        // Register the httpts scheme with our factory
        registry.register(new Scheme("httpts", sf, 443));
        HttpParams params = new BasicHttpParams();
        params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 3);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, 3);
        return new SingleClientConnManager(params, registry);
    }

    ClientConnectionManager clientConnectionManager = clientConnectionManagerMap.get(accountUUID);
    if (clientConnectionManager == null) {
        try {
            // Create a registry for our three schemes; http and https will
            // use built-in factories
            // And create a ccm with our registry
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

            if (accountUUID != null && INSTANCE.getFileStreamPath(accountUUID).exists()) {
                Log.d(TAG, "Create SSL factory with keystore");
                KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(
                        getPassword(accountUUID).toCharArray());
                KeyStore keyStore = KeyStore.Builder
                        .newInstance("pkcs12", null, INSTANCE.getFileStreamPath(accountUUID), protection)
                        .getKeyStore();
                registry.register(
                        new Scheme("https", new SSLSocketFactory(keyStore, getPassword(accountUUID)), 443));
            } else {
                Log.d(TAG, "Create regular SSL factory");
                registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            }
            // Use "insecure" socket factory.
            SSLSocketFactory sf = new SSLSocketFactory(SSLUtils.getSSLSocketFactory(true));
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            // Register the httpts scheme with our factory
            registry.register(new Scheme("httpts", sf, 443));

            HttpParams params = new BasicHttpParams();
            params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25);
            params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, SyncManager.sConnPerRoute);
            clientConnectionManager = new ThreadSafeClientConnManager(params, registry);
            clientConnectionManagerMap.put(accountUUID, clientConnectionManager);
        } catch (Exception e) {
            Log.e(TAG, "Error with keystore or something related!", e);
            throw new IllegalStateException(e);
        }
    }
    return clientConnectionManager;
}

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getserwerAPIdata(String SENSOR_KEY, String SENSOR_TOKEN, String INTERVAL)
        throws Exception, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    HttpClient httpclient2 = new DefaultHttpClient(cm, params);
    HttpParams httpParams = httpclient2.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);

    HttpResponse response = null;/*from   www  . jav  a2  s  .c  o m*/
    StatusLine statusLine2 = null;
    try {
        response = httpclient2.execute(new HttpGet("https://" + api_server_ip + "/sensor/" + SENSOR_KEY
                + "?version=1.0&token=" + SENSOR_TOKEN + "&interval=" + INTERVAL + "&unit=watt"));
        statusLine2 = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("failed ClientProtocolException");
    } catch (SocketTimeoutException ste) {
        ste.printStackTrace();
        throw new IOException("failed SocketTimeoutExeption");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("IO failed API Server down?");
    }

    if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString().replace("]", "").replace("[", "").replace("nan", "0")
                .replace("\"", "");

        String[] responseArray = responseString.split(",");
        Number[] responseArrayNumber = new Number[responseArray.length];
        for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
            responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
        }

        List<Number> series = Arrays.asList(responseArrayNumber);

        return series;

    } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine2.getReasonPhrase());
    }

}

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getserwerAPIdata_last2month(String SENSOR_KEY, String SENSOR_TOKEN)
        throws Exception, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    HttpClient httpclient2 = new DefaultHttpClient(cm, params);
    HttpParams httpParams = httpclient2.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);

    /*/*from  ww w.j  a  va  2s  .  c om*/
     * Get local UTC time (now) to request data to server
     */
    //TODO verify with Bart if shall request UTC or local time (guessed UTC)
    Date d = new Date(); // already return UTC
    //long moja_data = d.getTime() - (d.getTimezoneOffset() * 60 * 1000); // calculate
    // data/time
    // (milliseconds)
    // at local timzone
    //d.setTime(moja_data);

    d.setHours(00);
    d.setSeconds(00);
    d.setMinutes(00);

    HttpResponse response = null;
    StatusLine statusLine2 = null;
    try {
        response = httpclient2.execute(new HttpGet(
                "https://" + api_server_ip + "/sensor/" + SENSOR_KEY + "?version=1.0&token=" + SENSOR_TOKEN
                        + "&start=" + ((d.getTime() / 1000) - 5184000) + "&resolution=day&unit=watt"));

        statusLine2 = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("failed ClientProtocolException");
    } catch (SocketTimeoutException ste) {
        ste.printStackTrace();
        throw new IOException("failed SocketTimeoutExeption");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("IO failed API Server down?");
    }

    if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString().replace("]", "").replace("[", "").replace("nan", "0")
                .replace("\"", "");

        String[] responseArray = responseString.split(",");
        Number[] responseArrayNumber = new Number[responseArray.length];
        for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
            responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
        }

        List<Number> series = Arrays.asList(responseArrayNumber);

        return series;

    } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine2.getReasonPhrase());
    }

}

From source file:self.philbrown.droidQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled())
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {//from   www . java 2s.  c  o m
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(AjaxTask.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(AjaxTask.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.headers = null;
        return s;

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("droidQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (options.trustAllSSLCertificates()) {
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier(hostnameVerifier);
        schemeRegistry.register(new Scheme("https", socketFactory, 443));
        Log.w("Ajax", "Warning: All SSL Certificates have been trusted!");
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry);
    HttpClient client = new DefaultHttpClient(mgr, params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        final StatusLine statusLine = response.getStatusLine();

        final Function function = options.statusCode().get(statusLine.getStatusCode());
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusLine.getStatusCode(), options.clone());
                    else
                        function.invoke(null, statusLine.getStatusCode(), options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                parsedResponse = parseText(response);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    InputStream is = response.getEntity().getContent();
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(is, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(is, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    InputStream is = response.getEntity().getContent();

                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(is));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(response);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(response);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(response);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                parsedResponse = parseImage(response);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(response);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.headers = response.getAllHeaders();
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            Header[] lastModifiedHeaders = response.getHeaders("last-modified");
            if (lastModifiedHeaders.length >= 1) {
                try {
                    Header h = lastModifiedHeaders[0];
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h.getValue());
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.request = request;
                            error.options = options;
                            e.status = statusLine.getStatusCode();
                            e.reason = statusLine.getReasonPhrase();
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.headers = response.getAllHeaders();
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}