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:fr.dutra.confluence2wordpress.util.UrlUtils.java

/**
 * Sanitizes the given URL by escaping the path and query parameters, if necessary.
 * @see "http://stackoverflow.com/questions/724043/http-url-address-encoding-in-java"
 * @param url//from   w ww.j a  v  a  2 s.c  o  m
 * @return
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String sanitize(String url) throws URISyntaxException, MalformedURLException {
    URL temp = new URL(url);
    URI uri = new URI(temp.getProtocol(), temp.getUserInfo(), temp.getHost(), temp.getPort(), temp.getPath(),
            temp.getQuery(), temp.getRef());
    return uri.toASCIIString();
}

From source file:io.seldon.importer.articles.AttributesImporterUtils.java

public static String getBaseUrl(String url) throws Exception {
    URL aURL = new URL(url);

    String protocol = aURL.getProtocol();
    String host = aURL.getHost();
    String path = aURL.getPath();

    String baseUrl = String.format("%s://%s%s", protocol, host, path);
    return baseUrl;
}

From source file:SageCollegeProject.guideBox.java

public static String GetEncWebCall(String webcall) {
    try {/*from   w  ww . j  a v a2  s . co  m*/
        URL url = new URL(webcall);
        URI test = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return test.toASCIIString();
    } catch (URISyntaxException | MalformedURLException ex) {
        Logger.getLogger(guideBox.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.npower.dl.DownloadFactory.java

/**
 * Extract Server URL: //w  ww  . j  a v  a  2 s .  c  o m
 * http(s)://server:port
 * 
 * @param requestURL
 * @return
 * @throws MalformedURLException
 */
public static String getServerURL(String requestURL) throws MalformedURLException {
    URL url = new URL(requestURL);
    String protocol = url.getProtocol();
    String server = url.getHost();
    int port = url.getPort();
    if (port <= 0) {
        if (protocol.equalsIgnoreCase("https")) {
            port = 443;
        } else {
            port = 80;
        }
    }
    String serverURL = protocol + "://" + server + ":" + port;
    return serverURL;
}

From source file:com.blackducksoftware.integration.hub.jenkins.helper.BuildHelper.java

public static HubIntRestService getRestService(final IntLogger logger, final String serverUrl,
        final String username, final String password, final int hubTimeout) throws BDJenkinsHubPluginException,
        HubIntegrationException, URISyntaxException, MalformedURLException, BDRestException {
    final HubIntRestService service = new HubIntRestService(serverUrl);
    service.setLogger(logger);/*from   w ww.  j  a v  a2  s.co  m*/
    service.setTimeout(hubTimeout);
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        final ProxyConfiguration proxyConfig = jenkins.proxy;
        if (proxyConfig != null) {

            final URL actualUrl = new URL(serverUrl);

            final Proxy proxy = ProxyConfiguration.createProxy(actualUrl.getHost(), proxyConfig.name,
                    proxyConfig.port, proxyConfig.noProxyHost);

            if (proxy.address() != null) {
                final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
                if (StringUtils.isNotBlank(proxyAddress.getHostName()) && proxyAddress.getPort() != 0) {
                    if (StringUtils.isNotBlank(jenkins.proxy.getUserName())
                            && StringUtils.isNotBlank(jenkins.proxy.getPassword())) {
                        service.setProxyProperties(proxyAddress.getHostName(), proxyAddress.getPort(), null,
                                jenkins.proxy.getUserName(), jenkins.proxy.getPassword());
                    } else {
                        service.setProxyProperties(proxyAddress.getHostName(), proxyAddress.getPort(), null,
                                null, null);
                    }
                    if (logger != null) {
                        logger.debug("Using proxy: '" + proxyAddress.getHostName() + "' at Port: '"
                                + proxyAddress.getPort() + "'");
                    }
                }
            }
        }
    }
    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        service.setCookies(username, password);
    }

    return service;
}

From source file:com.liusoft.dlog4j.xml.RSSFetcher.java

/**
 * ??//w w  w.j  av  a  2  s  .co m
 * @param type
 * @param url
 * @return
 * @throws IOException 
 * @throws HttpException 
 * @throws SAXException 
 * @throws ParseException 
 */
private static Channel fetchChannelViaHTTP(String url) throws HttpException, IOException, SAXException {
    Digester parser = new XMLDigester();
    GetMethod get = new GetMethod(url);
    //get.setRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; zh-cn) Opera 8.52");
    try {
        http_client.executeMethod(get);
        if (get.getStatusCode() == HttpServletResponse.SC_OK) {
            Charset cs = null;
            Header header_cs = getResponseHeader(get, "Content-Type");
            if (header_cs == null) {
                cs = Charset.forName(get.getResponseCharSet());
            } else {
                String content_type = header_cs.getValue().toLowerCase();
                try {
                    Object[] values = content_type_parser.parse(content_type);
                    cs = Charset.forName((String) values[1]);
                } catch (ParseException e) {
                    URL o_url = new URL(url);
                    String host = o_url.getHost();
                    Iterator hosts = charsets.keySet().iterator();
                    while (hosts.hasNext()) {
                        String t_host = (String) hosts.next();
                        if (host.toLowerCase().endsWith(t_host)) {
                            cs = Charset.forName((String) charsets.get(t_host));
                            break;
                        }
                    }
                    if (cs == null)
                        cs = default_charset;

                }
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), cs));

            char[] cbuf = new char[1];
            int read_idx = 1;
            do {
                rd.mark(read_idx++);
                if (rd.read(cbuf) == -1)
                    break;
                if (cbuf[0] != '<')
                    continue;
                rd.reset();
                break;
            } while (true);
            return (Channel) parser.parse(rd);
        } else {
            log.error("Fetch RSS from " + url + " failed, code=" + get.getStatusCode());
        }
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:com.sldeditor.ui.detail.config.symboltype.externalgraphic.RelativePath.java

/**
 * Checks for host.//from  w w  w. ja  v a2 s. c om
 *
 * @param url the url
 * @return true, if successful
 */
public static boolean hasHost(URL url) {
    if (url == null) {
        return false;
    }
    String host = url.getHost();
    return host != null && !"".equals(host);
}

From source file:dk.dr.radio.net.Diverse.java

/**
   * Tjek for om vi er p et netvrk der krver login eller lignende.
   * Se 'Handling Network Sign-On' i http://developer.android.com/reference/java/net/HttpHttpURLConnection.html
   *///  w ww.  j  a va  2  s  .c  om
  private static void tjekOmdirigering(URL u, HttpURLConnection urlConnection) throws IOException {
      URL u2 = urlConnection.getURL();
      if (!u.getHost().equals(u2.getHost())) {
          // Vi blev omdirigeret
          Log.d("tjekOmdirigering " + u);
          Log.d("tjekOmdirigering " + u2);
          //Log.rapporterFejl(omdirigeringsfejl);
          throw new UnknownHostException("Der blev omdirigeret fra " + u.getHost() + " til " + u2.getHost());
      }
  }

From source file:com.digitalpebble.stormcrawler.protocol.HttpRobotRulesParser.java

/**
 * Compose unique key to store and access robot rules in cache for given URL
 *///from  ww w . ja  va  2  s  .  co  m
protected static String getCacheKey(URL url) {
    String protocol = url.getProtocol().toLowerCase(Locale.ROOT);
    String host = url.getHost().toLowerCase(Locale.ROOT);

    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
    }
    /*
     * Robot rules apply only to host, protocol, and port where robots.txt
     * is hosted (cf. NUTCH-1752). Consequently
     */
    String cacheKey = protocol + ":" + host + ":" + port;
    return cacheKey;
}

From source file:com.eviware.soapui.impl.wsdl.support.http.ProxyUtils.java

public static HostConfiguration initProxySettings(Settings settings, HttpState httpState,
        HostConfiguration hostConfiguration, String urlString, PropertyExpansionContext context) {
    boolean enabled = proxyEnabled;

    // check system properties first
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (proxyHost == null && enabled)
        proxyHost = PropertyExpander.expandProperties(context, settings.getString(ProxySettings.HOST, ""));
    if (proxyPort == null && proxyHost != null && enabled)
        proxyPort = PropertyExpander.expandProperties(context, settings.getString(ProxySettings.PORT, ""));

    if (!StringUtils.isNullOrEmpty(proxyHost) && !StringUtils.isNullOrEmpty(proxyPort)) {
        // check excludes
        String[] excludes = PropertyExpander
                .expandProperties(context, settings.getString(ProxySettings.EXCLUDES, "")).split(",");

        try {/*from w  w  w .j  av  a2  s .  c  o m*/
            URL url = new URL(urlString);

            if (!excludes(excludes, url.getHost(), url.getPort())) {
                hostConfiguration.setProxy(proxyHost, Integer.parseInt(proxyPort));

                String proxyUsername = PropertyExpander.expandProperties(context,
                        settings.getString(ProxySettings.USERNAME, null));
                String proxyPassword = PropertyExpander.expandProperties(context,
                        settings.getString(ProxySettings.PASSWORD, null));

                if (proxyUsername != null && proxyPassword != null) {
                    Credentials proxyCreds = new UsernamePasswordCredentials(proxyUsername,
                            proxyPassword == null ? "" : proxyPassword);

                    // check for nt-username
                    int ix = proxyUsername.indexOf('\\');
                    if (ix > 0) {
                        String domain = proxyUsername.substring(0, ix);
                        if (proxyUsername.length() > ix + 1) {
                            String user = proxyUsername.substring(ix + 1);
                            proxyCreds = new NTCredentials(user, proxyPassword, proxyHost, domain);
                        }
                    }

                    httpState.setProxyCredentials(AuthScope.ANY, proxyCreds);
                }
            }
        } catch (MalformedURLException e) {
            SoapUI.logError(e);
        }
    }

    return hostConfiguration;
}