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(HttpContext httpContext) 

Source Link

Usage

From source file:android.net.http.Connection.java

protected Connection(Context context, HttpHost host, RequestFeeder requestFeeder) {
    mContext = context;//from w  w w  .  j  a va  2  s.  c  om
    mHost = host;
    mRequestFeeder = requestFeeder;

    mCanPersist = false;
    mHttpContext = new BasicHttpContext(null);
}

From source file:android.core.TestHttpClient.java

public TestHttpClient() {
    super();//from w  ww. j a v a2 s  .  c o m
    this.params = new BasicHttpParams();
    this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
            .setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");

    this.httpproc = new BasicHttpProcessor();
    // Required protocol interceptors
    this.httpproc.addInterceptor(new RequestContent());
    this.httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    this.httpproc.addInterceptor(new RequestConnControl());
    this.httpproc.addInterceptor(new RequestUserAgent());
    this.httpproc.addInterceptor(new RequestExpectContinue());

    this.httpexecutor = new HttpRequestExecutor();
    this.connStrategy = new DefaultConnectionReuseStrategy();
    this.context = new BasicHttpContext(null);
}

From source file:org.apache.axis2.transport.http.server.DefaultConnectionListener.java

public void run() {
    try {//from   ww w  .  j ava2 s  .  co  m
        while (!Thread.interrupted()) {
            try {
                if (serversocket == null || serversocket.isClosed()) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Listening on port " + port);
                    }
                    serversocket = new ServerSocket(port);
                    serversocket.setReuseAddress(true);
                }
                LOG.debug("Waiting for incoming HTTP connection");
                Socket socket = this.serversocket.accept();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Incoming HTTP connection from " + socket.getRemoteSocketAddress());
                }
                AxisHttpConnection conn = new AxisHttpConnectionImpl(socket, this.params);
                try {
                    this.connmanager.process(conn);
                } catch (RejectedExecutionException e) {
                    conn.sendResponse(new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_0,
                            HttpStatus.SC_SERVICE_UNAVAILABLE, new BasicHttpContext(null)));
                }
            } catch (java.io.InterruptedIOException ie) {
                break;
            } catch (Throwable ex) {
                if (Thread.interrupted()) {
                    break;
                }
                if (!failureHandler.failed(this, ex)) {
                    break;
                }
            }
        }
    } finally {
        destroy();
    }
}

From source file:com.couchbase.client.ClusterManager.java

/**
 * Creates a connection to the Couchbase REST interface.
 *
 * @param uris A list of servers in the cluster.
 * @param username The cluster admin user name.
 * @param password The cluster admin password.
 *//*from  w w w  . java  2 s.com*/
public ClusterManager(List<URI> uris, String username, String password) {
    addrs = uris;
    user = username;
    pass = password;

    httpproc = new ImmutableHttpProcessor(
            new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(),
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    httpexecutor = new HttpRequestExecutor();
    context = new BasicHttpContext(null);
    conn = new DefaultHttpClientConnection();
}

From source file:com.k42b3.aletheia.protocol.http.HttpProtocol.java

public void setRequest(com.k42b3.aletheia.protocol.Request request, CallbackInterface callback)
        throws Exception {
    super.setRequest(request, callback);

    // request settings
    int port = request.getUrl().getPort();

    if (port == -1) {
        if (request.getUrl().getProtocol().equalsIgnoreCase("https")) {
            port = 443;/* w w  w . j a v a 2  s.  c  o  m*/
        } else {
            port = 80;
        }
    }

    context = new BasicHttpContext(null);
    host = new HttpHost(request.getUrl().getHost(), port);

    conn = new DefaultHttpClientConnection();
    connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
}

From source file:org.fourthline.cling.transport.impl.apache.HttpServerConnectionUpnpStream.java

public void run() {

    try {//from  w w  w.ja  v a  2s  .co m
        while (!Thread.interrupted() && connection.isOpen()) {
            log.fine("Handling request on open connection...");
            HttpContext context = new BasicHttpContext(null);
            httpService.handleRequest(connection, context);
        }
    } catch (ConnectionClosedException ex) {
        log.fine("Client closed connection");
        responseException(ex);
    } catch (SocketTimeoutException ex) {
        log.fine("Server-side closed socket (this is 'normal' behavior of Apache HTTP Core!): "
                + ex.getMessage());
    } catch (IOException ex) {
        log.warning("I/O exception during HTTP request processing: " + ex.getMessage());
        responseException(ex);
    } catch (HttpException ex) {
        throw new UnsupportedDataException("Request malformed: " + ex.getMessage(), ex);
    } finally {
        try {
            connection.shutdown();
        } catch (IOException ex) {
            log.fine("Error closing connection: " + ex.getMessage());
        }
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {//from w  w  w  . ja  va  2  s .c  o m
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "")
                .replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);

        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }

        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }/*from  ww w. j  av a 2s  .  c  o  m*/

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL openSearchServerURL = new URL(openSearchServerURLStr);
        String host = openSearchServerURL.getHost();
        int port = openSearchServerURL.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpHost httpHost = new HttpHost(host, port);

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

        try {
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);
                if (paramValue != null) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (firstParam) {
                    openSearchServerURLStr += "?";
                    firstParam = false;
                } else {
                    openSearchServerURLStr += "&";
                }
                openSearchServerURLStr += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host, port);
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET",
                    openSearchServerURLStr);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (RuntimeException e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:httpclient.conn.ManagerConnectDirect.java

/**
 * Creates a context for executing a request.
 * Since this example doesn't really use the execution framework,
 * the context can be left empty./*ww  w  . j ava  2 s.  co m*/
 *
 * @return  a new, empty context
 */
private final static HttpContext createContext() {
    return new BasicHttpContext(null);
}