Example usage for java.net URL getHost

List of usage examples for java.net URL getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Gets the host name of this URL , if applicable.

Usage

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, boolean redirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    HttpClientBuilder builder = getHttpClientBuilder();

    // redirect/* w ww . j a v a  2  s . co  m*/
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    if (timeout > 0)
        Http.setTimeout(builder, TimeSpanImpl.fromMillis(timeout));
    HttpContext context = setCredentials(builder, hh, username, password, false);
    setProxy(builder, request, proxy);
    CloseableHttpClient client = builder.build();
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, client.execute(request, context));
}

From source file:com.microsoftopentechnologies.windowsazurestorage.WAStorageClient.java

/**
 * Generates SAS URL for blob in Azure storage account
 *
 * @param storageAccount//from   w  w w. j a v  a2 s . c om
 * @param blobName
 * @param containerName container name
 * @return SAS URL
 * @throws Exception
 */
public static String generateSASURL(StorageAccountInfo storageAccount, String containerName, String blobName)
        throws Exception {
    String storageAccountName = storageAccount.getStorageAccName();
    StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(storageAccountName,
            storageAccount.getStorageAccountKey());
    URL blobURL = new URL(storageAccount.getBlobEndPointURL());
    String saBlobURI = new StringBuilder().append(blobURL.getProtocol()).append("://")
            .append(storageAccountName).append(".").append(blobURL.getHost()).append("/").toString();
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(credentials, new URI(saBlobURI),
            new URI(getCustomURI(storageAccountName, QUEUE, saBlobURI)),
            new URI(getCustomURI(storageAccountName, TABLE, saBlobURI)));
    // Create the blob client.
    CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference(containerName);

    // At this point need to throw an error back since container itself did not exist.
    if (!container.exists()) {
        throw new Exception("WAStorageClient: generateSASURL: Container " + containerName
                + " does not exist in storage account " + storageAccountName);
    }

    CloudBlob blob = container.getBlockBlobReference(blobName);
    String sas = blob.generateSharedAccessSignature(generatePolicy(), null);

    return sas;
}

From source file:de.tor.tribes.util.OBSTReportSender.java

public static void sendReport(URL pTarget, String pData) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host = new HttpHost(pTarget.getHost(), pTarget.getPort());

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

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

    try {/* w  ww .j  a  v  a 2  s .c om*/
        HttpEntity[] requestBodies = { new StringEntity(pData) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    pTarget.getPath() + "?" + pTarget.getQuery());

            request.setEntity(requestBodies[i]);
            // System.out.println(">> Request URI: " + request.getRequestLine().getUri());

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

            //   System.out.println("<< Response: " + response.getStatusLine());
            // System.out.println(EntityUtils.toString(response.getEntity()));
            // System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Returns a new HttpClient host configuration, initialized based on the specified request.
 * @param webRequest the request to use to initialize the returned host configuration
 * @return a new HttpClient host configuration, initialized based on the specified request
 *///from   ww w.j  a va  2 s .  c  o m
private static HttpHost getHostConfiguration(final WebRequest webRequest) {
    final URL url = webRequest.getUrl();
    return new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
}

From source file:fr.eolya.utils.http.HttpUtils.java

private static String getUrlHost(String url) {
    try {//from w  w  w .  ja  v a  2 s .  co  m
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
        URL u = new URL(url);
        return u.getHost();
    } catch (Exception e) {
        return "";
    }
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcap2Adapter.java

public static List<InetAddress> getHostAddresses(URL location) throws UnknownHostException {
    return getHostAddresses(location.getHost());
}

From source file:org.wso2.carbon.appmgt.gateway.utils.GatewayUtils.java

public static String getAppRootURL(MessageContext messageContext) {

    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();

    try {//from   w w  w. j a  va2 s .com

        // SERVICE_PREFIX gives the URL of the root. e.g. https://192.168.0.1:8243

        // WARNING : Service prefix always gives the IP address even if the request is made with a host name.
        // So we should only get the protocol from the service prefix.

        String servicePrefix = axis2MessageContext.getProperty("SERVICE_PREFIX").toString();
        URL serverRootURL = new URL(servicePrefix);
        String protocol = serverRootURL.getProtocol();

        // Get the published gateway URL for the protocol
        Environment defaultGatewayEnv = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration()
                .getApiGatewayEnvironments().get(0);

        String commaSeparatedGatewayEndpoints = defaultGatewayEnv.getApiGatewayEndpoint();
        String[] gatewayEndpoints = commaSeparatedGatewayEndpoints.split(",");

        URL gatewayEndpointURL = null;
        for (String gatewayEndpoint : gatewayEndpoints) {
            URL parsedEndpointURL = new URL(gatewayEndpoint);

            if (parsedEndpointURL.getProtocol().equals(protocol)) {
                gatewayEndpointURL = parsedEndpointURL;
                break;
            }
        }

        String webAppContext = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
        String webAppVersion = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);

        URL appRootURL = new URL(gatewayEndpointURL.getProtocol(), gatewayEndpointURL.getHost(),
                gatewayEndpointURL.getPort(), webAppContext + "/" + webAppVersion + "/");
        return appRootURL.toString();
    } catch (MalformedURLException e) {
        log.error("Error occurred while constructing the app root URL.", e);
        return null;
    }
}

From source file:fr.eolya.utils.http.HttpUtils.java

/**
 * Encode url/*from  w w  w.j av a 2s .c  o m*/
 * 
 * @param url url to be encoded
 * @return 
 */
public static String urlEncode(String url) {
    try {
        URL u = new URL(url);
        String host = u.getHost();
        int indexFile = url.indexOf("/", url.indexOf(host));
        if (indexFile == -1)
            return url;

        String urlFile = u.getFile();
        urlFile = URLDecoder.decode(urlFile, "UTF-8");

        String protocol = u.getProtocol();
        int port = u.getPort();
        if (port != -1 && port != 80 && "http".equals(protocol))
            host += ":".concat(String.valueOf(port));
        if (port != -1 && port != 443 && "https".equals(protocol))
            host += ":".concat(String.valueOf(port));

        URI uri = new URI(u.getProtocol(), host, urlFile, null);
        String ret = uri.toASCIIString();
        ret = ret.replaceAll("%3F", "?");
        return ret;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified port.
 * @param u the URL on which to base the returned URL
 * @param newPort the new port to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified port
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*www . java  2  s.  co  m*/
public static URL getUrlWithNewPort(final URL u, final int newPort) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getUserInfo(), u.getHost(), newPort, u.getPath(), u.getRef(),
            u.getQuery());
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPProxyConfigurator.java

/**
 * Check whether http proxy is configured or active. This is not a deep
 * check.//from w w w  . j a  v  a2s.  c o m
 *
 * @param messageContext
 *            in message context
 * @param targetURL
 *            URL of the edpoint which we are sending the request
 * @return true if proxy is enabled, false otherwise
 */
public static boolean isProxyEnabled(MessageContext messageContext, URL targetURL) {
    boolean proxyEnabled = false;

    Parameter param = messageContext.getConfigurationContext().getAxisConfiguration()
            .getParameter(HTTPTransportConstants.ATTR_PROXY);

    // If configuration is over ridden
    Object obj = messageContext.getProperty(HTTPConstants.PROXY);

    // From Java Networking Properties
    String sp = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST);

    if (param != null || obj != null || sp != null) {
        proxyEnabled = true;
    }

    boolean isNonProxyHost = validateNonProxyHosts(targetURL.getHost());

    return proxyEnabled && !isNonProxyHost;
}