Search in sources :

Example 66 with HttpContext

use of org.apache.http.protocol.HttpContext in project undertow by undertow-io.

the class SimpleConfidentialRedirectTestCase method simpleRedirectTestCase.

@Test
public void simpleRedirectTestCase() throws IOException, GeneralSecurityException {
    TestHttpClient client = new TestHttpClient();
    // create our own context to force http-request.config
    // notice that, if we just create http context, the config is ovewritten before request is sent
    // if we add the config to the HttpClient instead, it is ignored
    HttpContext httpContext = new BasicHttpContext() {

        private final RequestConfig config = RequestConfig.copy(RequestConfig.DEFAULT).setNormalizeUri(false).build();

        @Override
        public void setAttribute(final String id, final Object obj) {
            if ("http.request-config".equals(id))
                return;
            super.setAttribute(id, obj);
        }

        @Override
        public Object getAttribute(final String id) {
            if ("http.request-config".equals(id))
                return config;
            return super.getAttribute(id);
        }
    };
    client.setSSLContext(DefaultServer.getClientSSLContext());
    try {
        sendRequest(client, httpContext, "/foo", null);
        sendRequest(client, httpContext, "/foo+bar", null);
        sendRequest(client, httpContext, "/foo+bar;aa", null);
        sendRequest(client, httpContext, "/foo+bar;aa", "x=y");
        sendRequest(client, httpContext, "/foo+bar%3Aaa", "x=%3Ablah");
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpString(io.undertow.util.HttpString) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Example 67 with HttpContext

use of org.apache.http.protocol.HttpContext in project ABPlayer by winkstu.

the class HttpUtil method getCookie.

public static int getCookie(String url) {
    System.out.println("getCookie" + url);
    HttpGet httpGet = new HttpGet(hostBase + url);
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.setRedirectHandler(new RedirectHandler() {

            @Override
            public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                return false;
            }

            @Override
            public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
                return null;
            }
        });
        HttpResponse response = httpClient.execute(httpGet);
        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println(EntityUtils.toString(response.getEntity(), HTTP.UTF_8) + "add");
        if (response.getStatusLine().getStatusCode() == 200) {
            Header[] heads = response.getAllHeaders();
            System.out.println(heads.length);
            for (Header header : heads) {
                System.out.println(header.getName() + " = " + header.getValue());
            }
            return 2;
        } else if (response.getStatusLine().getStatusCode() == 302) {
            Header[] headers = response.getHeaders("Location");
            if (headers != null && headers.length > 0) {
                System.out.println(headers[0].getValue());
                return 3;
            }
        } else if (response.getStatusLine().getStatusCode() == 404) {
            return -1;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 1;
}
Also used : ProtocolException(org.apache.http.ProtocolException) ClientProtocolException(org.apache.http.client.ClientProtocolException) Header(org.apache.http.Header) RedirectHandler(org.apache.http.client.RedirectHandler) HttpGet(org.apache.http.client.methods.HttpGet) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ProtocolException(org.apache.http.ProtocolException) ClientProtocolException(org.apache.http.client.ClientProtocolException) DataFormatException(java.util.zip.DataFormatException) ConnectException(java.net.ConnectException) IOException(java.io.IOException)

Example 68 with HttpContext

use of org.apache.http.protocol.HttpContext in project ABPlayer by winkstu.

the class HttpUtil method GetCookie.

public static Integer GetCookie(String url, String number, String pw, String select, String host) {
    System.out.println("GetCookie");
    int result = 4;
    HttpPost httpPost = new HttpPost(hostBase + url);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("number", number));
    nvps.add(new BasicNameValuePair("passwd", pw));
    nvps.add(new BasicNameValuePair("select", select));
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
    HttpConnectionParams.setSoTimeout(httpParams, 10000);
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        httpClient.setRedirectHandler(new RedirectHandler() {

            @Override
            public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                return false;
            }

            @Override
            public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
                return null;
            }
        });
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(httpPost);
        System.out.println(response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == 200) {
            return 2;
        } else if (response.getStatusLine().getStatusCode() == 302) {
            Header[] headers = response.getHeaders("Location");
            if (headers != null && headers.length > 0) {
                List<Cookie> list = httpClient.getCookieStore().getCookies();
                for (Cookie c : list) {
                    cookieName = c.getName();
                    cookieValue = c.getValue();
                }
                System.out.println(cookieName + cookieValue);
                return 3;
            }
        } else if (response.getStatusLine().getStatusCode() == 404) {
            return -1;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Also used : Cookie(org.apache.http.cookie.Cookie) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) ProtocolException(org.apache.http.ProtocolException) ClientProtocolException(org.apache.http.client.ClientProtocolException) RedirectHandler(org.apache.http.client.RedirectHandler) ArrayList(java.util.ArrayList) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ProtocolException(org.apache.http.ProtocolException) ClientProtocolException(org.apache.http.client.ClientProtocolException) DataFormatException(java.util.zip.DataFormatException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) List(java.util.List) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 69 with HttpContext

use of org.apache.http.protocol.HttpContext in project SmartAndroidSource by jaychou2012.

the class AbstractAjaxCallback method httpDo.

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = client.execute(hr, context);
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);
    File file = null;
    if (code < 200 || code >= 300) {
        try {
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            // AQUtility.time("copy");
            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
            // AQUtility.timeEnd("copy", 0);
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 70 with HttpContext

use of org.apache.http.protocol.HttpContext in project ribbon by Netflix.

the class RestClient method apacheHttpClientSpecificInitialization.

protected Client apacheHttpClientSpecificInitialization() {
    httpClient4 = NFHttpClientFactory.getNamedNFHttpClient(restClientName, this.ncc, true);
    if (httpClient4 instanceof AbstractHttpClient) {
        // DONT use our NFHttpClient's default Retry Handler since we have
        // retry handling (same server/next server) in RestClient itself
        ((AbstractHttpClient) httpClient4).setHttpRequestRetryHandler(new NFHttpMethodRetryHandler(restClientName, 0, false, 0));
    } else {
        logger.warn("Unexpected error: Unable to disable NFHttpClient " + "retry handler, this most likely will not cause an " + "issue but probably should be looked at");
    }
    HttpParams httpClientParams = httpClient4.getParams();
    // initialize Connection Manager cleanup facility
    NFHttpClient nfHttpClient = (NFHttpClient) httpClient4;
    // should we enable connection cleanup for idle connections?
    try {
        enableConnectionPoolCleanerTask = ncc.getOrDefault(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled);
        nfHttpClient.getConnPoolCleaner().setEnableConnectionPoolCleanerTask(enableConnectionPoolCleanerTask);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, e1);
    }
    if (enableConnectionPoolCleanerTask) {
        try {
            connectionCleanerRepeatInterval = ncc.getOrDefault(CommonClientConfigKey.ConnectionCleanerRepeatInterval);
            nfHttpClient.getConnPoolCleaner().setConnectionCleanerRepeatInterval(connectionCleanerRepeatInterval);
        } catch (Exception e1) {
            throwInvalidValue(CommonClientConfigKey.ConnectionCleanerRepeatInterval, e1);
        }
        try {
            connIdleEvictTimeMilliSeconds = ncc.getDynamicProperty(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds);
            nfHttpClient.setConnIdleEvictTimeMilliSeconds(connIdleEvictTimeMilliSeconds);
        } catch (Exception e1) {
            throwInvalidValue(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, e1);
        }
        nfHttpClient.initConnectionCleanerTask();
    }
    try {
        maxConnectionsperHost = ncc.getOrDefault(CommonClientConfigKey.MaxHttpConnectionsPerHost);
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setDefaultMaxPerRoute(maxConnectionsperHost);
        }
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.MaxHttpConnectionsPerHost, e1);
    }
    try {
        maxTotalConnections = ncc.getOrDefault(CommonClientConfigKey.MaxTotalHttpConnections);
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setMaxTotal(maxTotalConnections);
        }
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.MaxTotalHttpConnections, e1);
    }
    try {
        connectionTimeout = ncc.getOrDefault(CommonClientConfigKey.ConnectTimeout);
        HttpConnectionParams.setConnectionTimeout(httpClientParams, connectionTimeout);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ConnectTimeout, e1);
    }
    try {
        readTimeout = ncc.getOrDefault(CommonClientConfigKey.ReadTimeout);
        HttpConnectionParams.setSoTimeout(httpClientParams, readTimeout);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ReadTimeout, e1);
    }
    // httpclient 4 seems to only have one buffer size controlling both
    // send/receive - so let's take the bigger of the two values and use
    // it as buffer size
    int bufferSize = Integer.MIN_VALUE;
    if (ncc.get(CommonClientConfigKey.ReceiveBufferSize) != null) {
        try {
            bufferSize = ncc.getOrDefault(CommonClientConfigKey.ReceiveBufferSize);
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.ReceiveBufferSize, e);
        }
        if (ncc.get(CommonClientConfigKey.SendBufferSize) != null) {
            try {
                int sendBufferSize = ncc.getOrDefault(CommonClientConfigKey.SendBufferSize);
                if (sendBufferSize > bufferSize) {
                    bufferSize = sendBufferSize;
                }
            } catch (Exception e) {
                throwInvalidValue(CommonClientConfigKey.SendBufferSize, e);
            }
        }
    }
    if (bufferSize != Integer.MIN_VALUE) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams, bufferSize);
    }
    if (ncc.get(CommonClientConfigKey.StaleCheckingEnabled) != null) {
        try {
            HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.StaleCheckingEnabled));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.StaleCheckingEnabled, e);
        }
    }
    if (ncc.get(CommonClientConfigKey.Linger) != null) {
        try {
            HttpConnectionParams.setLinger(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.Linger));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.Linger, e);
        }
    }
    if (ncc.get(CommonClientConfigKey.ProxyHost) != null) {
        try {
            proxyHost = (String) ncc.getOrDefault(CommonClientConfigKey.ProxyHost);
            proxyPort = ncc.getOrDefault(CommonClientConfigKey.ProxyPort);
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClient4.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.ProxyHost, e);
        }
    }
    if (isSecure) {
        final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore);
        final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore);
        final ClientConnectionManager currentManager = httpClient4.getConnectionManager();
        AbstractSslContextFactory abstractFactory = null;
        if (// if client is not is not required, we only need a keystore OR a truststore to warrant configuring
        (isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null)) || (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null))) {
            try {
                abstractFactory = new URLSslContextFactory(trustStoreUrl, ncc.get(CommonClientConfigKey.TrustStorePassword), keyStoreUrl, ncc.get(CommonClientConfigKey.KeyStorePassword));
            } catch (ClientSslSocketFactoryException e) {
                throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
            }
        }
        KeyStoreAwareSocketFactory awareSocketFactory;
        try {
            awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractFactory) : new KeyStoreAwareSocketFactory(abstractFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            currentManager.getSchemeRegistry().register(new Scheme("https", 443, awareSocketFactory));
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
        }
    }
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html
    if (ignoreUserToken) {
        ((DefaultHttpClient) httpClient4).setUserTokenHandler(new UserTokenHandler() {

            @Override
            public Object getUserToken(HttpContext context) {
                return null;
            }
        });
    }
    // custom SSL Factory handler
    String customSSLFactoryClassName = ncc.get(CommonClientConfigKey.CustomSSLSocketFactoryClassName);
    if (customSSLFactoryClassName != null) {
        try {
            SSLSocketFactory customSocketFactory = (SSLSocketFactory) ClientFactory.instantiateInstanceWithClientConfig(customSSLFactoryClassName, ncc);
            httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, customSocketFactory));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.CustomSSLSocketFactoryClassName, e);
        }
    }
    ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpClient4, new BasicCookieStore(), false);
    return new ApacheHttpClient4(handler, config);
}
Also used : ApacheHttpClient4Handler(com.sun.jersey.client.apache4.ApacheHttpClient4Handler) Scheme(org.apache.http.conn.scheme.Scheme) AbstractSslContextFactory(com.netflix.client.ssl.AbstractSslContextFactory) NFHttpClient(com.netflix.http4.NFHttpClient) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) KeyStoreAwareSocketFactory(com.netflix.http4.ssl.KeyStoreAwareSocketFactory) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) ApacheHttpClient4(com.sun.jersey.client.apache4.ApacheHttpClient4) UserTokenHandler(org.apache.http.client.UserTokenHandler) NFHttpMethodRetryHandler(com.netflix.http4.NFHttpMethodRetryHandler) ClientSslSocketFactoryException(com.netflix.client.ssl.ClientSslSocketFactoryException) HttpContext(org.apache.http.protocol.HttpContext) URLSslContextFactory(com.netflix.client.ssl.URLSslContextFactory) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) URISyntaxException(java.net.URISyntaxException) ClientException(com.netflix.client.ClientException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) ClientSslSocketFactoryException(com.netflix.client.ssl.ClientSslSocketFactoryException) AbstractHttpClient(org.apache.http.impl.client.AbstractHttpClient) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)

Aggregations

HttpContext (org.apache.http.protocol.HttpContext)169 HttpResponse (org.apache.http.HttpResponse)77 IOException (java.io.IOException)72 HttpRequest (org.apache.http.HttpRequest)55 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)47 HttpException (org.apache.http.HttpException)30 Test (org.junit.Test)29 HttpGet (org.apache.http.client.methods.HttpGet)27 HttpHost (org.apache.http.HttpHost)26 HttpPost (org.apache.http.client.methods.HttpPost)26 ArrayList (java.util.ArrayList)22 Header (org.apache.http.Header)21 StringEntity (org.apache.http.entity.StringEntity)21 NameValuePair (org.apache.http.NameValuePair)18 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)18 ProtocolException (org.apache.http.ProtocolException)17 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)17 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)17 URI (java.net.URI)16 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)16