Example usage for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory.

Prototype

public static SSLSocketFactory getSocketFactory() throws SSLInitializationException 

Source Link

Document

Obtains default SSL socket factory with an SSL context based on the standard JSSE trust material (cacerts file in the security properties directory).

Usage

From source file:org.restlet.ext.httpclient.HttpClientHelper.java

/**
 * Configures the scheme registry. By default, it registers the HTTP and the
 * HTTPS schemes.//  www. j a v  a 2s.  c  om
 * 
 * @param schemeRegistry
 *            The scheme registry to configure.
 */
protected void configure(SchemeRegistry schemeRegistry) {
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // [ifndef android]
    SSLSocketFactory sslSocketFactory = null;
    SslContextFactory sslContextFactory = SslUtils.getSslContextFactory(this);

    if (sslContextFactory != null) {
        try {
            SSLContext sslContext = sslContextFactory.createSslContext();
            sslSocketFactory = new SSLSocketFactory(sslContext);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create SSLContext.", e);
        }
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    if (getHostnameVerifier() != null) {
        try {
            X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) Engine
                    .loadClass(getHostnameVerifier()).newInstance();
            sslSocketFactory.setHostnameVerifier(hostnameVerifier);
        } catch (Exception e) {
            getLogger().log(Level.WARNING,
                    "An error occurred during the instantiation of the hostname verifier.", e);
        }
    }

    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));
    // [enddef]
}

From source file:org.springframework.http.client.HttpComponentsClientHttpRequestFactory.java

/**
 * Create a new instance of the {@code HttpComponentsClientHttpRequestFactory} with a default {@link HttpClient} that
 * uses a default {@link org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager}
 *//* ww  w.j a va2 s.c  o m*/
public HttpComponentsClientHttpRequestFactory() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

    httpClient = new DefaultHttpClient(connectionManager);
    this.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtilTest.java

@Test
public void testGetHttpClient() throws Exception {
    Log log = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    Mockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log);

    SSLSocketFactory socketFactory = Mockito.mock(SSLSocketFactory.class);
    PowerMockito.mockStatic(SSLSocketFactory.class);
    Mockito.when(SSLSocketFactory.getSocketFactory()).thenReturn(socketFactory);

    ServiceReferenceHolderMockCreator holderMockCreator = new ServiceReferenceHolderMockCreator(1);
    ServiceReferenceHolderMockCreator.initContextService();

    HttpClient client = APIUtil.getHttpClient(3244, "http");

    Assert.assertNotNull(client);//  w w  w.j a  v  a  2 s  .c o m
    Scheme scheme = client.getConnectionManager().getSchemeRegistry().get("http");
    Assert.assertEquals(3244, scheme.getDefaultPort());

    client = APIUtil.getHttpClient(3244, "https");
    Assert.assertNotNull(client);
    scheme = client.getConnectionManager().getSchemeRegistry().get("https");
    Assert.assertEquals(3244, scheme.getDefaultPort());

    client = APIUtil.getHttpClient(-1, "http");
    Assert.assertNotNull(client);
    scheme = client.getConnectionManager().getSchemeRegistry().get("http");
    Assert.assertEquals(80, scheme.getDefaultPort());

    client = APIUtil.getHttpClient(-1, "https");
    Assert.assertNotNull(client);
    scheme = client.getConnectionManager().getSchemeRegistry().get("https");
    Assert.assertEquals(443, scheme.getDefaultPort());
}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtilTest.java

@Test
public void testGetHttpClientIgnoreHostNameVerify() throws Exception {
    Log log = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    Mockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log);

    SSLSocketFactory socketFactory = Mockito.mock(SSLSocketFactory.class);
    PowerMockito.mockStatic(SSLSocketFactory.class);
    Mockito.when(SSLSocketFactory.getSocketFactory()).thenReturn(socketFactory);

    ServiceReferenceHolderMockCreator holderMockCreator = new ServiceReferenceHolderMockCreator(1);
    ServiceReferenceHolderMockCreator.initContextService();

    System.setProperty("httpclient.hostnameVerifier", "DefaultAndLocalhost");
    HttpClient client = APIUtil.getHttpClient(3244, "https");

    Assert.assertNotNull(client);//  w  w  w.  j av  a2 s.  co m
}

From source file:org.wso2.carbon.appmgt.keymgt.service.APIKeyMgtSubscriberService.java

/**
 * Renew the ApplicationAccesstoken, Call Token endpoint and get parameters.
 * Revoke old token.//from  w ww .j  a  v a 2 s.  co m
 * 
 * @param tokenType
 * @param oldAccessToken
 * @param allowedDomains
 * @param clientId
 * @param clientSecret
 * @param validityTime
 * @return
 * @throws Exception
 */

public String renewAccessToken(String tokenType, String oldAccessToken, String[] allowedDomains,
        String clientId, String clientSecret, String validityTime) throws Exception {
    String newAccessToken = null;
    long validityPeriod = 0;
    // create a post request to getNewAccessToken for client_credentials
    // grant type.

    //String tokenEndpoint = OAuthServerConfiguration.getInstance().getTokenEndPoint();
    String tokenEndpointName = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_TOKEN_ENDPOINT_NAME);
    String keyMgtServerURL = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_URL);
    URL keymgtURL = new URL(keyMgtServerURL);
    int keyMgtPort = keymgtURL.getPort();
    String tokenEndpoint = null;

    if (keyMgtServerURL != null) {
        String[] tmp = keyMgtServerURL.split("services");
        tokenEndpoint = tmp[0] + tokenEndpointName;
    }

    String revokeEndpoint = tokenEndpoint.replace("token", "revoke");

    // Below code is to overcome host name verification failure we get in certificate
    // validation due to self-signed certificate.
    X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(hostnameVerifier);
    if (keyMgtPort >= 0) {
        registry.register(new Scheme("https", keyMgtPort, socketFactory));
    } else {
        registry.register(new Scheme("https", 443, socketFactory));
    }
    SingleClientConnManager mgr1 = new SingleClientConnManager(registry);
    SingleClientConnManager mgr2 = new SingleClientConnManager(registry);

    HttpClient tokenEPClient = new DefaultHttpClient(mgr1, client.getParams());
    HttpClient revokeEPClient = new DefaultHttpClient(mgr2, client.getParams());
    HttpPost httpTokpost = new HttpPost(tokenEndpoint);
    HttpPost httpRevokepost = new HttpPost(revokeEndpoint);

    // Request parameters.
    List<NameValuePair> tokParams = new ArrayList<NameValuePair>(3);
    List<NameValuePair> revokeParams = new ArrayList<NameValuePair>(3);

    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS));
    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId));
    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret));

    revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId));
    revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret));
    revokeParams.add(new BasicNameValuePair("token", oldAccessToken));

    try {
        //Revoke the Old Access Token
        httpRevokepost.setEntity(new UrlEncodedFormEntity(revokeParams, "UTF-8"));
        HttpResponse revokeResponse = tokenEPClient.execute(httpRevokepost);

        if (revokeResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + revokeResponse.getStatusLine().getStatusCode());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Successfully revoked old application access token");
            }
        }

        //Generate New Access Token
        httpTokpost.setEntity(new UrlEncodedFormEntity(tokParams, "UTF-8"));
        HttpResponse tokResponse = revokeEPClient.execute(httpTokpost);
        HttpEntity tokEntity = tokResponse.getEntity();

        if (tokResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + tokResponse.getStatusLine().getStatusCode());
        } else {
            String responseStr = EntityUtils.toString(tokEntity);
            JSONObject obj = new JSONObject(responseStr);
            newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).toString();
            validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString());

            if (validityTime != null && !"".equals(validityTime)) {
                validityPeriod = Long.parseLong(validityTime);
            }
        }
    } catch (Exception e2) {
        String errMsg = "Error in getting new accessToken";
        log.error(errMsg);
        throw new APIKeyMgtException(errMsg, e2);

    }
    AppMDAO appMDAO = new AppMDAO();
    appMDAO.updateRefreshedApplicationAccessToken(tokenType, newAccessToken, validityPeriod);
    return newAccessToken;

}

From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java

/**
 * Initializes the httpClient./*from   w ww  . j a  v  a  2  s  .  c  om*/
 */
public static void initialize() throws XPathExpressionException {

    DefaultHttpClient client = new DefaultHttpClient();

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    Scheme sch = new Scheme("https", 443, socketFactory);
    ClientConnectionManager mgr = client.getConnectionManager();
    mgr.getSchemeRegistry().register(sch);
    httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:rapture.common.client.BaseHttpApi.java

private static HttpClient getHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // Increase max total connection to 200
    cm.setMaxTotal(200);//w  w  w .  jav a2s .c  o  m
    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);
    // Increase max connections for localhost:80 to 50
    HttpHost localhost = new HttpHost("locahost", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm);
    // Use a proxy if it is defined - we need to pass this on to the
    // HttpClient
    if (System.getProperties().containsKey("http.proxyHost")) {
        String host = System.getProperty("http.proxyHost");
        String port = System.getProperty("http.proxyPort", "8080");
        HttpHost proxy = new HttpHost(host, Integer.parseInt(port));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

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

    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            if (log.isTraceEnabled()) {
                log.trace("Response Headers:");
                for (Header h : response.getAllHeaders()) {
                    log.trace(h.getName() + " : " + h.getValue());
                }
            }
            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;
                        }
                    }
                }
            }
        }

    });

    return httpClient;
}

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   w w w. j a  va 2  s. co 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;
    }
}