Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext.

Prototype

public BasicHttpContext() 

Source Link

Usage

From source file:com.uroad.net.AsyncHttpClient.java

public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("uroad-android-httpclient/%s (http://www.u-road.com/)", VERSION));
    //Scheme??"http""https"???
    //??socket??java.net.SocketSchemeRegistry?Schemes?
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    //HTTPClient??
    //?/*from  w  w  w.  j a va  2  s .  c  o m*/
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });
    //??
    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE,
            DEFAULT_KEEP_ALIVETIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.CallerRunsPolicy());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java

/**
 * Makes a request after setting the user agent and verifies that the session cookie is NOT set.
 *///w ww .  j a  v  a 2s  .  c om
private void testCookieNotSetForKnownStateLessClients(final String userAgent) throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";
    URI uri = new URI(url);

    Header header = new BasicHeader("User-Agent", userAgent + "/1.6"); // user agent plus some version

    DefaultHttpClient httpClient = new DefaultHttpClient();

    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(header);
    assertThat(executeAndRelease(httpClient, getMethod, localcontext), equalTo(200));

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    assertThat("Session Cookie should not be set for user agent: " + userAgent, sessionCookie, nullValue());
}

From source file:com.neudesic.azureservicebustest.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   w w w  .  j a va2 s .  co m*/
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }

            request.addHeader("Accept", "*/*"); // SVG 5/8/2013 - intercept this to add for our API
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testTarget() throws Exception {
    HttpContext localContext = new BasicHttpContext();
    responses.add(new BasicHttpResponse(_200));
    client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }/*  w  w  w  .  ja  v a  2 s.  c o  m*/
    }, localContext);
    HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null);
    assertEquals("http://example.com/200", root.resolve(req.getURI()).toASCIIString());
}

From source file:com.applicake.beanstalkclient.utils.AndroidHttpClient.java

private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override//ww  w.  ja v a 2 s  . c o  m
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);

            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            return context;
        }
    };
}

From source file:com.woonoz.proxy.servlet.HttpRequestHandler.java

private void performHttpRequest(HttpRequestBase requestToServer, HttpServletResponse responseToClient,
        ServerHeadersHandler serverHeadersHandler) throws IOException, URISyntaxException {
    HttpContext context = new BasicHttpContext();
    context.setAttribute(HttpRequestHandler.class.getName(), this);
    HttpResponse responseFromServer = client.execute(requestToServer, context);
    logger.debug("Performed request: {} --> {}", requestToServer.getRequestLine(),
            responseFromServer.getStatusLine());
    responseToClient.setStatus(responseFromServer.getStatusLine().getStatusCode());
    copyHeaders(responseFromServer, responseToClient, serverHeadersHandler);
    HttpEntity entity = responseFromServer.getEntity();
    if (entity != null) {
        try {//from   w  w w  .j a  v a2 s . c o  m
            entity.writeTo(responseToClient.getOutputStream());
        } finally {
            EntityUtils.consume(entity);
        }
    }
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as byte[] throws {@link RuntimeException} If anything
 * goes wrong/*w  ww.j a va 2s .  c o m*/
 * 
 * @return The content of the URL as a byte[]
 * @throws java.io.IOException
 */
public byte[] getDataAsByteArray(String url, CredentialsProvider cp) throws IOException {
    HttpClient httpClient = getNewHttpClient();

    URL urlObj = new URL(url);
    HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());

    HttpContext credContext = new BasicHttpContext();
    credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

    HttpGet job = new HttpGet(url);
    HttpResponse response = httpClient.execute(host, job, credContext);

    HttpEntity entity = response.getEntity();
    return EntityUtils.toByteArray(entity);
}

From source file:com.jkoolcloud.jesl.net.http.HttpClient.java

/**
 * {@inheritDoc}/*  w  w w.j ava2 s .  c  o m*/
 */
@Override
public synchronized void connect() throws IOException {
    try {
        if (secure) {
            SSLSocketFactory ssf = null;
            if (!StringUtils.isEmpty(sslKeystore)) {
                SSLContextFactory scf = new SSLContextFactory(sslKeystore, sslKeystorePwd, sslKeystorePwd);
                ssf = new SSLSocketFactory(scf.getSslContext(true));
            } else {
                ssf = new SSLSocketFactory(SSLContext.getDefault());
            }
            Scheme secureScheme = new Scheme("https", port, ssf);
            schemeReg = new SchemeRegistry();
            schemeReg.register(secureScheme);
        }
        route = new HttpRoute(httpHost, null, httpProxy, secure, RouteInfo.TunnelType.PLAIN,
                RouteInfo.LayerType.PLAIN);
        if (schemeReg != null) {
            connMgr = new BasicClientConnectionManager(schemeReg);
        } else {
            connMgr = new BasicClientConnectionManager();
        }
        connReq = connMgr.requestConnection(route, null);
        connection = connReq.getConnection(0, null);
        connection.open(route, new BasicHttpContext(), new BasicHttpParams());
        logger.log(OpLevel.DEBUG, "Connected to {0}{1}", uri,
                (httpProxy != null ? " via proxy " + httpProxy : ""));
    } catch (Throwable e) {
        close();
        throw new IOException("Failed to connect to uri=" + uri + ", reason=" + e.getMessage(), e);
    }
}

From source file:com.android.ePerion.gallery.mapEperion.GoogleMapEperion.java

/**
 * Get a list of GeoPoint in order to draw the driving direction between two geoPoint.
 * @param lat1 Latitude of the source geoPoint.
 * @param lon1 Longitude of the source geoPoint.
 * @param lat2 Latitude of the destination.
 * @param lon2 Longitude of the destination.
 * @return A list of geoPoints.//from   w  ww.j a v a  2 s .c om
 */
public ArrayList<GeoPoint> getDirections(double lat1, double lon1, double lat2, double lon2) {
    //URL to send to the Google Map API in order to get the route between two points.
    String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1
            + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
    String tag[] = { "lat", "lng" };
    ArrayList<GeoPoint> list_of_geopoints = new ArrayList<GeoPoint>();
    HttpResponse response = null;
    //Send the HTTP request to the servers.
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        //Parse the XML document, returned by the Google API, to store the geoPoints extracted.
        if (doc != null) {
            NodeList nl1, nl2;
            nl1 = doc.getElementsByTagName(tag[0]);
            nl2 = doc.getElementsByTagName(tag[1]);
            if (nl1.getLength() > 0) {
                list_of_geopoints = new ArrayList<GeoPoint>();
                for (int i = 0; i < nl1.getLength(); i++) {
                    Node node1 = nl1.item(i);
                    Node node2 = nl2.item(i);
                    double lat = Double.parseDouble(node1.getTextContent());
                    double lng = Double.parseDouble(node2.getTextContent());
                    list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
                }
            } else {
                // No points found
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list_of_geopoints;
}

From source file:com.photowall.oauth.util.BaseHttpClient.java

private BaseHttpClient(Context mContext, ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override/*  w w w.  j  av  a 2s .  co  m*/
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);
            processor.addRequestInterceptor(new CurlLogger());

            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            return context;
        }

    };

    /*?*/
    setProxy(mContext);
}