Example usage for org.apache.http.message BasicHttpRequest addHeader

List of usage examples for org.apache.http.message BasicHttpRequest addHeader

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpRequest addHeader.

Prototype

public void addHeader(Header header) 

Source Link

Usage

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;// w  w  w .  ja v a2  s .c  o  m
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from  w w w . j  a v  a  2s  . c  o  m*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from www.  j ava  2  s  .c om*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", props.getProperty("apiToken"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());

    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for CR\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/* w  ww  . j a va 2 s  . co  m*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

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

/**
 * Opens the connection to a http server or proxy.
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *//*from w w  w .ja  v a2  s.c om*/
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

            proxySock.setSoTimeout(60 * 1000);

            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);

            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }

            throw new IOException(errorMessage);
        }

        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

            // add all 'proxy' headers from the original request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) {
                    proxyReq.addHeader(h);
                }
            }

            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();

            // it is possible to receive informational status
            // codes prior to receiving actual headers;
            // all those status codes are smaller than OK 200
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        }

        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(),
                        mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }

                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();

            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode,
                    statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();

            proxyConnection.close();

            // here, we return null to indicate that the original
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket();

            sslSock.setSoTimeout(SOCKET_TIMEOUT);
            sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()));
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }

            throw new IOException(errorMessage);
        }
    }

    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this,
            sslSock, mHost.getHostName());

    // Inform the user if there is a problem
    if (error != null) {
        // handleSslErrorRequest may immediately unsuspend if it wants to
        // allow the certificate anyway.
        // So we mark the connection as suspended, call handleSslErrorRequest
        // then check if we're still suspended and only wait if we actually
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():"
                                    + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                    // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
}

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

/**
 * Opens the connection to a http server or proxy.
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *//*from  w w  w . j  ava 2 s.  co m*/
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

            proxySock.setSoTimeout(60 * 1000);

            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);

            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }

            throw new IOException(errorMessage);
        }

        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

            // add all 'proxy' headers from the original request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) {
                    proxyReq.addHeader(h);
                }
            }

            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();

            // it is possible to receive informational status
            // codes prior to receiving actual headers;
            // all those status codes are smaller than OK 200
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        }

        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(),
                        mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }

                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();

            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode,
                    statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();

            proxyConnection.close();

            // here, we return null to indicate that the original
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket();

            sslSock.setSoTimeout(SOCKET_TIMEOUT);
            sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()));
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }

            throw new IOException(errorMessage);
        }
    }

    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this,
            sslSock, mHost.getHostName());

    EventHandler eventHandler = req.getEventHandler();

    // Update the certificate info (to be consistent, it is better to do it
    // here, before we start handling SSL errors, if any)
    eventHandler.certificate(mCertificate);

    // Inform the user if there is a problem
    if (error != null) {
        // handleSslErrorRequest may immediately unsuspend if it wants to
        // allow the certificate anyway.
        // So we mark the connection as suspended, call handleSslErrorRequest
        // then check if we're still suspended and only wait if we actually
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = eventHandler.handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():"
                                    + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                    // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

/**
 * Opens the connection to a http server or proxy.
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *///  w  ww. jav  a2  s. c  o m
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    synchronized (HttpsConnection.class) {
        initializeEngine(null, req);
    }
    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

            proxySock.setSoTimeout(60 * 1000);

            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);

            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }

            throw new IOException(errorMessage);
        }

        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

            // add all 'proxy' headers from the original request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) {
                    proxyReq.addHeader(h);
                }
            }

            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();

            // it is possible to receive informational status
            // codes prior to receiving actual headers;
            // all those status codes are smaller than OK 200
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        }

        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(),
                        mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }

                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();

            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode,
                    statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();

            proxyConnection.close();

            // here, we return null to indicate that the original
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket();

            sslSock.setSoTimeout(SOCKET_TIMEOUT);
            sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()));
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }

            throw new IOException(errorMessage);
        }
    }

    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this,
            sslSock, mHost.getHostName());

    // Inform the user if there is a problem
    if (error != null) {
        // handleSslErrorRequest may immediately unsuspend if it wants to
        // allow the certificate anyway.
        // So we mark the connection as suspended, call handleSslErrorRequest
        // then check if we're still suspended and only wait if we actually
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():"
                                    + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                    // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
}

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

/**
 * Opens the connection to a http server or proxy.
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *//*from ww  w  . j av a  2  s .com*/
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

            proxySock.setSoTimeout(60 * 1000);

            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);

            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }

            throw new IOException(errorMessage);
        }

        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

            // add all 'proxy' headers from the original request, we also need
            // to add 'host' header unless we want proxy to answer us with a
            // 400 Bad Request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase(Locale.ROOT);
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive")
                        || headerName.equals("host")) {
                    proxyReq.addHeader(h);
                }
            }

            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();

            // it is possible to receive informational status
            // codes prior to receiving actual headers;
            // all those status codes are smaller than OK 200
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }

            throw new IOException(errorMessage);
        }

        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(),
                        mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }

                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();

            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode,
                    statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();

            proxyConnection.close();

            // here, we return null to indicate that the original
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
            sslSock.setSoTimeout(SOCKET_TIMEOUT);
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }

            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }

            throw new IOException(errorMessage);
        }
    }

    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this,
            sslSock, mHost.getHostName());

    // Inform the user if there is a problem
    if (error != null) {
        // handleSslErrorRequest may immediately unsuspend if it wants to
        // allow the certificate anyway.
        // So we mark the connection as suspended, call handleSslErrorRequest
        // then check if we're still suspended and only wait if we actually
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():"
                                    + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                    // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
}

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

public void run() {
    try {/*from  w  ww  . j  a  va 2s  . c  o  m*/
        // get socket
        Socket socket = this.getSocket();
        conn.bind(socket, params);

        // build request
        BasicHttpRequest request;

        if (!this.getRequest().getBody().isEmpty()) {
            request = new BasicHttpEntityEnclosingRequest(this.getRequest().getMethod(),
                    this.getRequest().getPath());
        } else {
            request = new BasicHttpRequest(this.getRequest().getMethod(), this.getRequest().getPath());
        }

        // add headers
        String boundary = null;
        ArrayList<String> ignoreHeader = new ArrayList<String>();
        ignoreHeader.add("Content-Length");
        ignoreHeader.add("Expect");

        LinkedList<Header> headers = this.getRequest().getHeaders();

        for (int i = 0; i < headers.size(); i++) {
            if (!ignoreHeader.contains(headers.get(i).getName())) {
                // if the content-type header gets set the conent-length
                // header is automatically added
                request.addHeader(headers.get(i));
            }

            if (headers.get(i).getName().equals("Content-Type")
                    && headers.get(i).getValue().startsWith("multipart/form-data")) {
                String header = headers.get(i).getValue().substring(headers.get(i).getValue().indexOf(";") + 1)
                        .trim();

                if (!header.isEmpty()) {
                    String parts[] = header.split("=");

                    if (parts.length >= 2) {
                        boundary = parts[1];
                    }
                }
            }
        }

        // set body
        if (request instanceof BasicHttpEntityEnclosingRequest && boundary != null) {
            boundary = "--" + boundary;
            StringBuilder body = new StringBuilder();
            String req = this.getRequest().getBody();

            int i = 0;
            String partHeader;
            String partBody;

            while ((i = req.indexOf(boundary, i)) != -1) {
                int hPos = req.indexOf("\n\n", i + 1);
                if (hPos != -1) {
                    partHeader = req.substring(i + boundary.length() + 1, hPos).trim();
                } else {
                    partHeader = null;
                }

                int bpos = req.indexOf(boundary, i + 1);
                if (bpos != -1) {
                    partBody = req.substring(hPos == -1 ? i : hPos + 2, bpos);
                } else {
                    partBody = req.substring(hPos == -1 ? i : hPos + 2);
                }

                if (partBody.equals(boundary + "--")) {
                    body.append(boundary + "--" + "\r\n");
                    break;
                } else if (!partBody.isEmpty()) {
                    body.append(boundary + "\r\n");
                    if (partHeader != null && !partHeader.isEmpty()) {
                        body.append(partHeader.replaceAll("\n", "\r\n"));
                        body.append("\r\n");
                        body.append("\r\n");
                    }
                    body.append(partBody);
                }

                i++;
            }

            this.getRequest().setBody(body.toString().replaceAll("\r\n", "\n"));

            HttpEntity entity = new StringEntity(this.getRequest().getBody());

            ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
        } else if (request instanceof BasicHttpEntityEnclosingRequest) {
            HttpEntity entity = new StringEntity(this.getRequest().getBody());

            ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
        }

        logger.info("> " + request.getRequestLine().getUri());

        // request
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);

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

        logger.info("< " + response.getStatusLine());

        // update request headers 
        LinkedList<Header> header = new LinkedList<Header>();
        Header[] allHeaders = request.getAllHeaders();

        for (int i = 0; i < allHeaders.length; i++) {
            header.add(allHeaders[i]);
        }

        this.getRequest().setHeaders(header);

        // create response
        this.response = new Response(response);

        // call callback
        callback.onResponse(this.request, this.response);
    } catch (Exception e) {
        Aletheia.handleException(e);
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
            Aletheia.handleException(e);
        }
    }
}