Example usage for java.net URL getPort

List of usage examples for java.net URL getPort

Introduction

In this page you can find the example usage for java.net URL getPort.

Prototype

public int getPort() 

Source Link

Document

Gets the port number of this URL .

Usage

From source file:nl.b3p.viewer.stripes.ProxyActionBean.java

private Resolution proxyArcIMS() throws Exception {

    HttpServletRequest request = getContext().getRequest();

    if (!"POST".equals(request.getMethod())) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }//from  w  w  w  . ja  va 2 s .  c o  m

    Map params = new HashMap(getContext().getRequest().getParameterMap());
    // Only allow these parameters in proxy request
    params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName"));
    URL theUrl = new URL(url);
    // Must not allow file / jar etc protocols, only HTTP:
    String path = theUrl.getPath();
    for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) {
        if (path.length() == theUrl.getPath().length()) {
            path += "?";
        } else {
            path += "&";
        }
        path += URLEncoder.encode(param.getKey(), "UTF-8") + "="
                + URLEncoder.encode(param.getValue()[0], "UTF-8");
    }
    theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);

    // TODO logging for inspecting malicious proxy use

    ByteArrayOutputStream post = new ByteArrayOutputStream();
    IOUtils.copy(request.getInputStream(), post);

    // This check makes some assumptions on how browsers serialize XML
    // created by OpenLayers' ArcXML.js write() function (whitespace etc.),
    // but all major browsers pass this check
    if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }

    final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    connection.connect();
    try {
        IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
    } finally {
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
    }

    return new StreamingResolution(connection.getContentType()) {
        @Override
        protected void stream(HttpServletResponse response) throws IOException {
            try {
                IOUtils.copy(connection.getInputStream(), response.getOutputStream());
            } finally {
                connection.disconnect();
            }

        }
    };
}

From source file:edu.internet2.middleware.shibboleth.common.config.metadata.HTTPMetadataProviderBeanDefinitionParser.java

/**
 * Sets the basic authentication properties, if any, for the HTTP client used to fetch metadata.
 * /*w  w  w.java2s  . com*/
 * @param httpClient the HTTP client
 * @param config the metadata provider configuration
 * @param providerId the ID of the metadata provider
 * @param metadataURL the URL from which metadata will be fetched
 */
protected void setHttpBasicAuthSettings(HttpClient httpClient, Element config, String providerId,
        URL metadataURL) {
    String authUser = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthUser"));
    if (authUser == null) {
        return;
    }
    log.debug("Metadata provider '{}' HTTP Basic Auth username: {}", providerId, authUser);

    String authPassword = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthPassword"));
    log.debug("Metadata provider '{}' HTTP Basic Auth password not show", providerId);

    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authUser, authPassword);
    AuthScope authScope = new AuthScope(metadataURL.getHost(), metadataURL.getPort());
    httpClient.getState().setCredentials(authScope, credentials);
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

private HttpRequest handleRequest(Socket proxySocket) throws IOException {
    HttpRequest request = new HttpRequest();
    BufferedInputStream proxyInStream = new BufferedInputStream(proxySocket.getInputStream());
    byte b = -1;//from   ww  w .j  a  v  a 2  s. c  om
    ArrayList<Byte> list = new ArrayList<Byte>(200);
    ArrayList<Byte> listToSend = new ArrayList<Byte>(200);
    int readInt;
    String previousLine = null;
    int lastCRPos = 0;
    int lastSendCRPos = 0;
    boolean hasCompleted = false;
    int lineNo = 0;
    int length = 0;
    while (!isInterrupted && !hasCompleted && (readInt = proxyInStream.read()) != -1) {
        b = (byte) readInt;
        list.add(new Byte(b));
        listToSend.add(new Byte(b));
        if (b == 13) {
            // check for two line breaks without form feed
            if (list.size() > 1) {
                if (list.get(list.size() - 2).equals(new Byte((byte) 13))) {
                    hasCompleted = true;
                } else {
                    // try to analyze the previous line
                    byte[] bytes = new byte[list.size() - lastCRPos - 1];
                    for (int i = lastCRPos; i < list.size() - 1; i++) {
                        bytes[i - lastCRPos] = ((Byte) list.get(i)).byteValue();
                    }
                    // requests are always in ASCII
                    previousLine = new String(bytes, "ISO-8859-1");
                    //logger.debug("request: " + previousLine);
                    if (lineNo == 0) {
                        // we must have here s.th. like 
                        // GET http://server/xyz.html?param=value HTTP/1.0
                        String[] components = previousLine.split(" ");
                        String method = components[0];
                        String urlStr = components[1];
                        String httpVersion = components[2];

                        // now parse the URL
                        URL url = new URL(urlStr);
                        String host = url.getHost();
                        String path = url.getPath();
                        String query = url.getQuery();
                        String port = String.valueOf(url.getPort());
                        if ("-1".equals(port)) {
                            port = "80";
                        }
                        request.setPort(Integer.parseInt(port));
                        request.setHost(host);
                        request.setPath(path);
                        request.setQuery(query);
                        request.setMethod(method);
                        request.setVersion(httpVersion);

                        // now we can reconstruct this line...
                        if ((System.getProperty("http.proxyHost") == null)
                                || System.getProperty("http.proxyHost").trim().equals("")) {
                            listToSend = new ArrayList<Byte>();
                            StringBuffer buff = new StringBuffer(100);
                            buff.append(method);
                            buff.append(' ');
                            buff.append(path);
                            if (query != null) {
                                buff.append('?');
                                buff.append(query);
                            }
                            buff.append(' ');
                            buff.append(components[2].substring(0, components[2].length()));
                            String newLine = buff.toString();
                            byte[] newLineBytes = newLine.getBytes("ISO-8859-1");
                            for (int i = 0; i < newLineBytes.length; i++) {
                                listToSend.add(new Byte(newLineBytes[i]));
                            }
                            listToSend.add(new Byte((byte) 13));
                        }
                    }
                    if (previousLine.matches("^[Cc]ontent-[Ll]ength: .+")) {
                        String lengthStr = previousLine.substring(16, previousLine.length());
                        length = Integer.parseInt(lengthStr);
                        //logger.debug("length: " + length + ", " + lengthStr);
                    }
                    if (previousLine.matches("^[Pp]roxy.+")) {
                        if ((System.getProperty("http.proxyHost") == null)
                                || System.getProperty("http.proxyHost").trim().equals("")) {
                            //logger.debug("proxy!!! - " + previousLine);
                            // if not used behind another proxy erase proxy-related headers
                            for (int i = listToSend.size() - 1; i > lastSendCRPos - 2; i--) {
                                listToSend.remove(i);
                            }
                        }
                    }
                    // the CR should be ignored for printing any headerLine
                    lastCRPos = list.size() + 1;
                    lastSendCRPos = listToSend.size() + 1;
                    lineNo++;
                }
            }
        }
        if (b == 10) {
            // check for two line breaks with form feed
            if (list.get(list.size() - 2).equals(new Byte((byte) 13))
                    && list.get(list.size() - 3).equals(new Byte((byte) 10))
                    && list.get(list.size() - 4).equals(new Byte((byte) 13))) {
                //logger.debug("length: " + length);
                if (length == 0) {
                    hasCompleted = true;
                } else {
                    for (int i = 0; i < length; i++) {
                        readInt = proxyInStream.read();
                        b = (byte) readInt;
                        list.add(new Byte(b));
                        listToSend.add(new Byte(b));
                    }
                    list.add(new Byte((byte) '\n'));
                    listToSend.add(new Byte((byte) '\n'));
                    hasCompleted = true;
                }
            }
        }
    }
    // store original request
    byte[] byteArray = getByteArrayFromList(listToSend);
    request.setRequest(byteArray);
    //logger.debug("request: \nasText:\n" + new String(byteArray) + "as bytes:\n" + printByteArray(byteArray));
    return request;
}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {/* w  w  w .  j  a va 2 s.c  o m*/
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java

/**
 * Constructs an HTTP client with user specified by the given credentials.
 *
 * @param url The URL for the Avatica server
 * @param credential The GSS credentials
 *///  www. ja v a  2s.c o m
public AvaticaCommonsHttpClientSpnegoImpl(URL url, GSSCredential credential) {
    this.url = Objects.requireNonNull(url);

    pool = new PoolingHttpClientConnectionManager();
    // Increase max total connection to 100
    final String maxCnxns = System.getProperty(CACHED_CONNECTIONS_MAX_KEY, CACHED_CONNECTIONS_MAX_DEFAULT);
    pool.setMaxTotal(Integer.parseInt(maxCnxns));
    // Increase default max connection per route to 25
    final String maxCnxnsPerRoute = System.getProperty(CACHED_CONNECTIONS_MAX_PER_ROUTE_KEY,
            CACHED_CONNECTIONS_MAX_PER_ROUTE_DEFAULT);
    pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));

    this.host = new HttpHost(url.getHost(), url.getPort());

    this.authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
            new SPNegoSchemeFactory(STRIP_PORT_ON_SERVER_LOOKUP, USE_CANONICAL_HOSTNAME)).build();

    this.credentialsProvider = new BasicCredentialsProvider();
    if (null != credential) {
        // Non-null credential should be used directly with KerberosCredentials.
        this.credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
    } else {
        // A null credential implies that the user is logged in via JAAS using the
        // java.security.auth.login.config system property
        this.credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
    }

    this.authCache = new BasicAuthCache();

    // A single thread-safe HttpClient, pooling connections via the ConnectionManager
    this.client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).setConnectionManager(pool)
            .build();
}

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

/**
 * getting host configuration to support standard http/s, proxy and NTLM support
 *
 * @param client active HttpClient//from   w  w w  .j  av a2s  .  co  m
 * @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 (PROTOCOL_HTTP.equals(protocol)) {
            port = 80;
        } else if (PROTOCOL_HTTPS.equals(protocol)) {
            port = 443;
        }

    }

    // to see the host is a proxy and in the proxy list - available in axis2.xml
    HostConfiguration 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 (HTTPProxyConfigurationUtil.isProxyEnabled(msgCtx, targetURL)) {
        if (log.isDebugEnabled()) {
            log.debug("Configuring HTTP proxy.");
        }
        HTTPProxyConfigurationUtil.configure(msgCtx, client, config);
    }

    return config;
}

From source file:com.rusticisoftware.tincan.RemoteLRS.java

@Override
public StatementsResultLRSResponse moreStatements(String moreURL) {
    if (moreURL == null) {
        return null;
    }//w w w .j  a v a2  s.co m

    // moreURL is relative to the endpoint's server root
    URL endpoint = this.getEndpoint();
    String url = endpoint.getProtocol() + "://" + endpoint.getHost()
            + (endpoint.getPort() == -1 ? "" : endpoint.getPort()) + moreURL;

    HTTPRequest request = new HTTPRequest();
    request.setResource(url);
    request.setMethod(HttpMethods.GET);
    HTTPResponse response = makeSyncRequest(request);

    StatementsResultLRSResponse lrsResponse = new StatementsResultLRSResponse(request, response);

    if (response.getStatus() == 200) {
        lrsResponse.setSuccess(true);
        try {
            lrsResponse.setContent(new StatementsResult(new StringOfJSON(response.getContent())));
        } catch (Exception ex) {
            lrsResponse.setErrMsg("Exception: " + ex.toString());
            lrsResponse.setSuccess(false);
        }
    } else {
        lrsResponse.setSuccess(false);
    }

    return lrsResponse;
}

From source file:com.funambol.server.engine.SyncAdapter.java

/**
 * Creates the RespURI using the given requestURL and the sessionID.
 * The responseURI is created using the same protocol, host, port and path of
 * the request.//from  w ww .  ja v  a  2 s. c  o m
 * @param requestURL the request url
 * @param sessionId the sessionId
 * @return String the responseURI. It is created use the same protocol, host,
 *                port and path of the request.
 * @throws MalformedURLException if an error occurs.
 */
private String getResponseUri(String requestURL, String sessionId) throws MalformedURLException {

    URL url = new URL(requestURL);

    String protocol = url.getProtocol();
    String server = url.getHost();
    int port = url.getPort();
    String path = url.getPath();
    int indexJsessionid = path.indexOf("jsessionid");

    //
    // Checks if the path contains a jsessionid. If so, we have to remove it.
    //
    if (indexJsessionid != -1) {
        path = path.substring(0, indexJsessionid);
        if (path.endsWith(";")) {
            path = path.substring(0, path.length() - 1);
        }
    }

    // Create StringBuffer with estimated size 128, in order to
    // avoid growing. Default size 16 is to short most likely.
    StringBuffer respURI = new StringBuffer(128);
    respURI.append(protocol).append("://").append(server);
    if (port != -1) {
        respURI.append(':').append(port);
    }
    respURI.append(path).append(";jsessionid=").append(sessionId);

    return respURI.toString();
}

From source file:com.twinsoft.convertigo.engine.proxy.translated.HttpClient.java

private byte[] getData(HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle)
        throws IOException, EngineException {
    byte[] result = null;

    try {//from  w  ww .jav a2s .com
        Context context = infoShuttle.context;

        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        HostConfiguration hostConfiguration = connector.hostConfiguration;

        boolean trustAllServerCertificates = connector.isTrustAllServerCertificates();

        // Retrieving httpState
        getHttpState(connector, infoShuttle);

        Engine.logEngine.trace("(HttpClient) Retrieving data as a bytes array...");
        Engine.logEngine.debug("(HttpClient) Connecting to: " + resourceUrl);

        // Proxy configuration
        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(HttpClient) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        Engine.logEngine.debug("(HttpClient) Https: " + connector.isHttps());
        CertificateManager certificateManager = connector.certificateManager;

        URL url = null;
        String host = "";
        int port = -1;
        if (resourceUrl.toLowerCase().startsWith("https:")) {
            Engine.logEngine.debug("(HttpClient) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);

            Engine.logEngine
                    .debug("(HttpClient) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logEngine.debug("(HttpClient) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            resourceUrl = url.getFile();
            Engine.logEngine.debug("(HttpClient) Updated URL for SSL purposes: " + resourceUrl);
        } else {
            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }

        Engine.logEngine.debug("(HttpClient) Building method on: " + resourceUrl);
        Engine.logEngine.debug("(HttpClient) postFromUser=" + infoShuttle.postFromUser);
        Engine.logEngine.debug("(HttpClient) postToSite=" + infoShuttle.postToSite);
        if (infoShuttle.postFromUser && infoShuttle.postToSite) {
            method = new PostMethod(resourceUrl);
            ((PostMethod) method).setRequestEntity(
                    new StringRequestEntity(infoShuttle.userPostData, infoShuttle.userContentType,
                            infoShuttle.context.httpServletRequest.getCharacterEncoding()));
        } else {
            method = new GetMethod(resourceUrl);
        }

        HttpMethodParams httpMethodParams = method.getParams();

        // Cookie configuration
        if (handleCookie) {
            Engine.logEngine.debug("(HttpClient) Setting cookie policy.");
            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        String basicUser = connector.getAuthUser();
        String basicPassword = connector.getAuthPassword();
        String givenBasicUser = connector.getGivenAuthUser();
        String givenBasicPassword = connector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(HttpClient) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(HttpClient) Proxy credentials: " + proxyUser + ":******");
        }

        // Setting HTTP headers
        Engine.logEngine.debug("(HttpClient) Incoming HTTP headers:");
        String headerName, headerValue;
        for (int k = 0, kSize = infoShuttle.userHeaderNames.size(); k < kSize; k++) {
            headerName = (String) infoShuttle.userHeaderNames.get(k);
            // Cookies are handled by HttpClient, so we do not have to proxy Cookie header
            // See #986 (Multiples cookies don't work with some proxies)
            if (headerName.toLowerCase().equals("cookie")) {
                Engine.logEngine.debug("Cookie header ignored");
            } else {
                headerValue = (String) infoShuttle.userHeaderValues.get(k);
                method.setRequestHeader(headerName, headerValue);
                Engine.logEngine.debug(headerName + "=" + headerValue);
            }
        }

        // Getting the result
        executeMethod(method, connector, resourceUrl, infoShuttle);
        result = method.getResponseBody();

    } finally {
        if (method != null)
            method.releaseConnection();
    }

    return result;
}