Example usage for org.apache.commons.httpclient HttpClient getHostConfiguration

List of usage examples for org.apache.commons.httpclient HttpClient getHostConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getHostConfiguration.

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:com.ning.http.client.providers.apache.TestableApacheAsyncHttpProvider.java

/**
 * This one we can get into/*  w  ww .j  ava2 s.c  o  m*/
 */
protected HttpMethodBase getHttpMethodBase(HttpClient client, Request request) throws IOException {
    String methodName = request.getMethod();
    HttpMethodBase method;
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            try (FileInputStream fis = new FileInputStream(file)) {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        if (request.getHeaders().getFirstValue("Expect") != null
                && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else {
        method = testMethodFactory.createMethod(methodName, request);
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultCredentials = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM),
                    defaultCredentials);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    if (isNonEmpty(request.getCookies())) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    if (request.getHeaders().getFirstValue("User-Agent") != null) {
        method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(TestableApacheAsyncHttpProvider.class));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (!acceptableEncodings.contains("gzip")) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;//from  ww  w .jav a2  s. com
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        if (request.getHeaders().getFirstValue("Expect") != null
                && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer()
            : config.getProxyServer();
    boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
    if (!avoidProxy) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }

    method.setFollowRedirects(false);
    if ((request.getCookies() != null) && !request.getCookies().isEmpty()) {
        for (Cookie cookie : request.getCookies()) {
            method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
        }
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    if (request.getHeaders().getFirstValue("User-Agent") != null) {
        method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:net.sourceforge.myvd.quickstart.util.GetSSLCert.java

public static javax.security.cert.X509Certificate getCert(String host, int port) {
    GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory();
    Protocol myhttps = new Protocol("https", certFactory, port);
    HttpClient httpclient = new HttpClient();
    httpclient.getHostConfiguration().setHost(host, port, myhttps);
    GetMethod httpget = new GetMethod("/");
    try {// w w  w.j a v a 2s. c  o  m
        httpclient.executeMethod(httpget);
        //System.out.println(httpget.getStatusLine());
    } catch (Throwable t) {
        //do nothing
    }

    finally {
        httpget.releaseConnection();
    }

    return certFactory.getCertificate();
}

From source file:net.sourceforge.squirrel_sql.fw.util.IOUtilitiesImpl.java

/**
 * Setup proxy configuration specified in proxySettings. This setup is skipped if: 1) proxySettings is
 * null. 2) proxySettings.getHttpUseProxy() is false (HttpClient doesn't support SOCKS proxy) 3) The url's
 * host component is in the "non-proxy" host list
 * //  w ww .j  av  a  2s . co m
 * @param proxySettings
 *           the ProxySettings to use
 * @param client
 *           the instance of HttpClient to configure
 * @param url
 *           the URL of the file to be retrieved
 */
private void setupProxy(IProxySettings proxySettings, HttpClient client, URL url) {
    if (proxySettings == null) {
        return;
    }
    if (!proxySettings.getHttpUseProxy()) {
        return;
    }
    if (proxySettings.getHttpNonProxyHosts() != null
            && proxySettings.getHttpNonProxyHosts().contains(url.getHost())) {
        return;
    }

    String proxyHost = proxySettings.getHttpProxyServer();
    int proxyPort = Integer.parseInt(proxySettings.getHttpProxyPort());
    String proxyUsername = proxySettings.getHttpProxyUser();
    String proxyPassword = proxySettings.getHttpProxyPassword();

    client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    if (proxyUsername != null && !"".equals(proxyUsername)) {
        Credentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
        client.getState().setProxyCredentials(AuthScope.ANY, credentials);
    }
}

From source file:net.ushkinaz.storm8.http.HttpClientProvider.java

@Override
public HttpClient get() {
    HttpClient httpClient = new HttpClient();

    if (System.getProperty(HTTP_PROXY_HOST) != null) {
        httpClient.getHostConfiguration().setProxy(System.getProperty(HTTP_PROXY_HOST),
                Integer.getInteger(HTTP_PROXY_PORT, 3128));
    }/*from w  ww  . ja va2  s. com*/
    return httpClient;
}

From source file:org.alfresco.httpclient.HttpClientFactory.java

protected HttpClient getHttpsClient(String httpsHost, int httpsPort) {
    // Configure a custom SSL socket factory that will enforce mutual authentication
    HttpClient httpClient = constructHttpClient();
    HttpHostFactory hostFactory = new HttpHostFactory(new Protocol("https", sslSocketFactory, httpsPort));
    httpClient.setHostConfiguration(new HostConfigurationWithHostFactory(hostFactory));
    httpClient.getHostConfiguration().setHost(httpsHost, httpsPort, "https");
    return httpClient;
}

From source file:org.alfresco.httpclient.HttpClientFactory.java

protected HttpClient getDefaultHttpClient(String httpHost, int httpPort) {
    HttpClient httpClient = constructHttpClient();
    httpClient.getHostConfiguration().setHost(httpHost, httpPort);
    return httpClient;
}

From source file:org.alfresco.httpclient.HttpClientFactory.java

protected HttpClient getMD5HttpClient(String host, int port) {
    HttpClient httpClient = constructHttpClient();
    httpClient.getHostConfiguration().setHost(host, port);
    return httpClient;
}

From source file:org.alfresco.repo.remoteconnector.RemoteConnectorServiceImpl.java

/**
 * Executes the specified request, and return the response
 *///w  ww  .  j  av a  2  s  . c  o  m
public RemoteConnectorResponse executeRequest(RemoteConnectorRequest request) throws IOException,
        AuthenticationException, RemoteConnectorClientException, RemoteConnectorServerException {
    RemoteConnectorRequestImpl reqImpl = (RemoteConnectorRequestImpl) request;
    HttpMethodBase httpRequest = reqImpl.getMethodInstance();

    // Attach the headers to the request
    for (Header hdr : request.getRequestHeaders()) {
        httpRequest.addRequestHeader(hdr);
    }

    // Attach the body, if possible
    if (httpRequest instanceof EntityEnclosingMethod) {
        if (request.getRequestBody() != null) {
            ((EntityEnclosingMethod) httpRequest).setRequestEntity(reqImpl.getRequestBody());
        }
    }

    // Grab our thread local HttpClient instance
    // Remember - we must then clean it up!
    HttpClient httpClient = HttpClientHelper.getHttpClient();

    // The url should already be vetted by the RemoteConnectorRequest
    URL url = new URL(request.getURL());

    // Use the appropriate Proxy Host if required
    if (httpProxyHost != null && url.getProtocol().equals("http") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTP proxy host for: " + url);
        if (httpProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpAuthScope, httpProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTP proxy credentials for proxy: " + httpProxyHost.getHostName());
        }
    } else if (httpsProxyHost != null && url.getProtocol().equals("https") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpsProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTPS proxy host for: " + url);
        if (httpsProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpsAuthScope, httpsProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTPS proxy credentials for proxy: " + httpsProxyHost.getHostName());
        }
    } else {
        //host should not be proxied remove any configured proxies
        httpClient.getHostConfiguration().setProxyHost(null);
        httpClient.getState().clearProxyCredentials();
    }

    // Log what we're doing
    if (logger.isDebugEnabled()) {
        logger.debug("Performing " + request.getMethod() + " request to " + request.getURL());
        for (Header hdr : request.getRequestHeaders()) {
            logger.debug("Header: " + hdr);
        }
        Object requestBody = null;
        if (request != null) {
            requestBody = request.getRequestBody();
        }
        if (requestBody != null && requestBody instanceof StringRequestEntity) {
            StringRequestEntity re = (StringRequestEntity) request.getRequestBody();
            logger.debug("Payload (string): " + re.getContent());
        } else if (requestBody != null && requestBody instanceof ByteArrayRequestEntity) {
            ByteArrayRequestEntity re = (ByteArrayRequestEntity) request.getRequestBody();
            logger.debug("Payload (byte array): " + re.getContent().toString());
        } else {
            logger.debug("Payload is not of a readable type.");
        }
    }

    // Perform the request, and wrap the response
    int status = -1;
    String statusText = null;
    RemoteConnectorResponse response = null;
    try {
        status = httpClient.executeMethod(httpRequest);
        statusText = httpRequest.getStatusText();

        Header[] responseHdrs = httpRequest.getResponseHeaders();
        Header responseContentTypeH = httpRequest
                .getResponseHeader(RemoteConnectorRequestImpl.HEADER_CONTENT_TYPE);
        String responseCharSet = httpRequest.getResponseCharSet();
        String responseContentType = (responseContentTypeH != null ? responseContentTypeH.getValue() : null);

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "response url=" + request.getURL() + ", length =" + httpRequest.getResponseContentLength()
                            + ", responceContentType " + responseContentType + ", statusText =" + statusText);
        }

        // Decide on how best to handle the response, based on the size
        // Ideally, we want to close the HttpClient resources immediately, but
        //  that isn't possible for very large responses
        // If we can close immediately, it makes cleanup simpler and fool-proof
        if (httpRequest.getResponseContentLength() > MAX_BUFFER_RESPONSE_SIZE
                || httpRequest.getResponseContentLength() == -1) {
            if (logger.isTraceEnabled()) {
                logger.trace("large response (or don't know length) url=" + request.getURL());
            }

            // Need to wrap the InputStream in something that'll close
            InputStream wrappedStream = new HttpClientReleasingInputStream(httpRequest);
            httpRequest = null;

            // Now build the response
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, wrappedStream);
        } else {
            if (logger.isTraceEnabled()) {
                logger.debug("small response for url=" + request.getURL());
            }
            // Fairly small response, just keep the bytes and make life simple
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, httpRequest.getResponseBody());

            // Now we have the bytes, we can close the HttpClient resources
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    } finally {
        // Make sure, problems or not, we always tidy up (if not large stream based)
        // This is important because we use a thread local HttpClient instance
        if (httpRequest != null) {
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    }

    // Log the response
    if (logger.isDebugEnabled())
        logger.debug("Response was " + status + " " + statusText);

    // Decide if we should throw an exception
    if (status >= 300) {
        // Tidy if needed
        if (httpRequest != null)
            httpRequest.releaseConnection();

        // Specific exceptions
        if (status == Status.STATUS_FORBIDDEN || status == Status.STATUS_UNAUTHORIZED) {
            // TODO Forbidden may need to be handled differently.
            // TODO Need to get error message into the AuthenticationException
            throw new AuthenticationException(statusText);
        }

        // Server side exceptions
        if (status >= 500 && status <= 599) {
            logger.error("executeRequest: remote connector server exception: [" + status + "] " + statusText);
            throw new RemoteConnectorServerException(status, statusText);
        }
        if (status == Status.STATUS_PRECONDITION_FAILED) {
            logger.error("executeRequest: remote connector client exception: [" + status + "] " + statusText);
            throw new RemoteConnectorClientException(status, statusText, response);
        } else {
            // Client request exceptions
            if (httpRequest != null) {
                // Response wasn't too big and is available, supply it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, response);
            } else {
                // Response was too large, report without it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, null);
            }
        }
    }

    // If we get here, then the request/response was all fine
    // So, return our created response
    return response;
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

/**
 * getting host configuration to support standard http/s, proxy and NTLM
 * support/*  ww  w .ja v a2 s  .  co  m*/
 * 
 * @param client
 *            active HttpClient
 * @param msgCtx
 *            active MessageContext
 * @param targetURL
 *            the target URL
 * @return a HostConfiguration set up with proxy information
 * @throws AxisFault
 *             if problems occur
 */
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext msgCtx, URL targetURL)
        throws AxisFault {

    boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx);
    int port = targetURL.getPort();

    String protocol = targetURL.getProtocol();
    if (port == -1) {
        if (HTTPTransportConstants.PROTOCOL_HTTP.equals(protocol)) {
            port = 80;
        } else if (HTTPTransportConstants.PROTOCOL_HTTPS.equals(protocol)) {
            port = 443;
        }

    }

    // to see the host is a proxy and in the proxy list - available in
    // axis2.xml
    HostConfiguration config = client.getHostConfiguration();
    if (config == null) {
        config = new HostConfiguration();
    }

    // one might need to set his own socket factory. Let's allow that case
    // as well.
    Protocol protocolHandler = (Protocol) msgCtx.getOptions()
            .getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);

    // setting the real host configuration
    // I assume the 90% case, or even 99% case will be no protocol handler
    // case.
    if (protocolHandler == null) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        config.setHost(targetURL.getHost(), port, protocolHandler);
    }

    if (isAuthenticationEnabled) {
        // Basic, Digest, NTLM and custom authentications.
        this.setAuthenticationInfo(client, msgCtx, config);
    }
    // proxy configuration

    if (HTTPProxyConfigurator.isProxyEnabled(msgCtx, targetURL)) {
        if (log.isDebugEnabled()) {
            log.debug("Configuring HTTP proxy.");
        }
        HTTPProxyConfigurator.configure(msgCtx, client, config);
    }

    return config;
}