List of usage examples for java.net URL getHost
public String getHost()
From source file:fr.eolya.utils.http.HttpUtils.java
public static String urlGetAbsoluteURL(String urlReferer, String urlHref) { try {/*from w ww . jav a2s .co m*/ if (urlHref.equals("")) return ""; // Case 1 : urlHref starts with "http://" if (urlHref.startsWith("http://") || urlHref.startsWith("https://")) { return urlHref; } URL url = new URL(urlReferer); // Case 1.1 : urlHref starts with "//" if (urlHref.startsWith("//")) { return url.getProtocol() + ":" + urlHref; } String urlRefererHost = url.getProtocol() + "://" + url.getHost(); if (url.getPort() != -1) { urlRefererHost = urlRefererHost + ":" + String.valueOf(url.getPort()); } // Case 2 : urlHref looks like "?..." if (urlHref.startsWith("?")) { // find "?" in urlReferer /* if (urlReferer.indexOf("?")!=-1) return urlReferer.substring(0,urlReferer.indexOf("?")) + urlHref; else return urlReferer + urlHref; */ return urlRefererHost + "/" + url.getPath() + urlHref; } // Case 3 : urlHref looks like "/path/file.html..." if (urlHref.startsWith("/")) { return urlRefererHost + urlHref; } // Case 4 : urlHref looks like "path/file.html..." String urlRefererPath = url.getPath(); if ("".equals(urlRefererPath)) urlRefererPath = "/"; //if (urlRefererPath.indexOf(".")==-1 && urlRefererPath.lastIndexOf("/") != urlRefererPath.length()-1) // urlRefererPath = urlRefererPath + "/"; int offset = urlRefererPath.lastIndexOf("/"); /* if (offset <= 0) { urlRefererPath = ""; } else { urlRefererPath = urlRefererPath.substring(0, offset); } */ urlRefererPath = urlRefererPath.substring(0, offset); return urlRefererHost + urlRefererPath + "/" + urlHref; } catch (Exception e) { //e.printStackTrace (); } return ""; }
From source file:com.adobe.ags.curly.controller.AuthHandler.java
private void loginTest() { CloseableHttpClient client = null;//from www .ja v a2 s . com try { if (!model.requiredFieldsPresentProperty().get()) { Platform.runLater(() -> { model.loginConfirmedProperty().set(false); model.statusMessageProperty().set(ApplicationState.getMessage(INCOMPLETE_FIELDS)); }); return; } String url = getUrlBase() + TEST_PAGE; URL testUrl = new URL(url); InetAddress address = InetAddress.getByName(testUrl.getHost()); if (address == null || isDnsRedirect(address)) { throw new UnknownHostException("Unknown host " + testUrl.getHost()); } Platform.runLater(() -> { model.loginConfirmedProperty().set(false); model.statusMessageProperty().set(ApplicationState.getMessage(ATTEMPTING_CONNECTION)); }); client = getAuthenticatedClient(); HttpGet loginTest = new HttpGet(url); HttpResponse response = client.execute(loginTest); StatusLine responseStatus = response.getStatusLine(); if (responseStatus.getStatusCode() >= 200 && responseStatus.getStatusCode() < 300) { Platform.runLater(() -> { model.loginConfirmedProperty().set(true); model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_SUCCESSFUL)); }); } else { Platform.runLater(() -> { model.loginConfirmedProperty().set(false); model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + responseStatus.getReasonPhrase() + " (" + responseStatus.getStatusCode() + ")"); }); } } catch (MalformedURLException | IllegalArgumentException | UnknownHostException ex) { Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex); Platform.runLater(() -> { model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + ex.getMessage()); model.loginConfirmedProperty().set(false); }); } catch (Throwable ex) { Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex); Platform.runLater(() -> { model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + ex.getMessage()); model.loginConfirmedProperty().set(false); }); } finally { if (client != null) { try { client.close(); } catch (IOException ex) { Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:com.github.ibm.domino.client.BaseClient.java
public void setAddress(String address) { try {//from ww w . j a va 2 s . co m URL url = new URL(address); setHost(url.getHost()); if (url.getPort() > 0) { setPort(url.getPort()); } setProtocol(url.getProtocol()); } catch (MalformedURLException ex) { Logger.getLogger(BaseClient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.comcast.cns.io.HTTPEndpointAsyncPublisher.java
@Override public void send() throws Exception { HttpAsyncRequester requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy(), httpParams);/*from w w w.j a v a2s.c o m*/ final URL url = new URL(endpoint); final HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getPath() + (url.getQuery() == null ? "" : "?" + url.getQuery())); composeHeader(request); String msg = null; if (message.getMessageStructure() == CNSMessageStructure.json) { msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http); } else { msg = message.getMessage(); } if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) { msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http); } logger.debug("event=send_async_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\""); request.setEntity(new NStringEntity(msg)); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), connectionPool, new BasicHttpContext(), new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { int statusCode = response.getStatusLine().getStatusCode(); // accept all 2xx status codes if (statusCode >= 200 && statusCode < 300) { callback.onSuccess(); } else { logger.warn(target + "://" + url.getPath() + "?" + url.getQuery() + " -> " + response.getStatusLine()); callback.onFailure(statusCode); } } public void failed(final Exception ex) { logger.warn(target + " " + url.getPath() + " " + url.getQuery(), ex); callback.onFailure(0); } public void cancelled() { logger.warn(target + " " + url.getPath() + " " + url.getQuery() + " -> " + "cancelled"); callback.onFailure(1); } }); }
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java
@Override public String call() throws IOException { String response = ""; ReviewInput reviewInput = createReview(); String reviewEndpoint = resolveEndpointURL(); HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint); if (httpPost == null) { return response; }//from w w w.ja v a2 s .co m CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(AuthScope.ANY, credentials); HttpHost proxy = null; if (httpProxy != null && !httpProxy.isEmpty()) { try { URL url = new URL(httpProxy); proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); if (altLogger != null) { altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage()); } } } HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultCredentialsProvider(credProvider); if (proxy != null) { builder.setProxy(proxy); } CloseableHttpClient httpClient = builder.build(); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase()); if (altLogger != null) { altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase()); } } } catch (Exception e) { logger.error("Failed to submit result to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString()); } } return response; }
From source file:no.kantega.kwashc.server.test.SSLProtocolTest.java
private HttpResponse checkClient(Site site, int httpsPort, HttpClient httpclient, String[] protocols, String[] ciphers) throws NoSuchAlgorithmException, KeyManagementException, IOException { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { allowAllTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000); SSLSocket socket = (SSLSocket) sf.createSocket(params); if (protocols != null) { socket.setEnabledProtocols(protocols); }/*from w w w . j a v a 2 s . co m*/ if (ciphers != null) { socket.setEnabledCipherSuites(ciphers); } URL url = new URL(site.getAddress()); InetSocketAddress address = new InetSocketAddress(url.getHost(), httpsPort); sf.connectSocket(socket, address, null, params); Scheme sch = new Scheme("https", httpsPort, sf); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet request = new HttpGet( "https://" + url.getHost() + ":" + site.getSecureport() + url.getPath() + "blog"); return httpclient.execute(request); }
From source file:com.collabnet.tracker.common.httpClient.TrackerHttpSender.java
@Override protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL url) { String httpUser = null;/*from w ww. j a v a2s .c o m*/ String httpPassword = null; String serverUrl = url.getProtocol() + "://" + url.getHost(); PTrackerWebServicesClient webServicesClient = TrackerClientManager.getInstance().getClient(serverUrl); Proxy proxy = Activator.getPlatformProxy(url.toString()); if (proxy != null) { proxy.setProxy(client); } httpUser = webServicesClient.getHttpUser(); httpPassword = webServicesClient.getHttpPassword(); setupHttpClient(client, url.toString(), httpUser, httpPassword); return client.getHostConfiguration(); }
From source file:br.ufsc.das.gtscted.shibbauth.Connection.java
public String[] httpGetWithEndpoint(String url) throws IOException { HttpGet httpget = new HttpGet(url); HttpContext context = new BasicHttpContext(); HttpResponse response = httpClient.execute(httpget, context); String responseAsStr = readResponse(response.getEntity().getContent()).toString(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException(response.getStatusLine().toString()); }/*from w ww . j a v a 2s.com*/ HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); URL endpointUrl = new URL(currentUrl); String endpointDomain = "https://" + endpointUrl.getHost(); String[] returnArray = { endpointDomain, responseAsStr }; return returnArray; }
From source file:uk.ac.ox.oucs.vle.TestPopulatorInput.java
public InputStream getInput(PopulatorContext context) { InputStream input;/* w w w . ja v a2 s .com*/ DefaultHttpClient httpclient = new DefaultHttpClient(); try { URL xcri = new URL(context.getURI()); if ("file".equals(xcri.getProtocol())) { input = xcri.openStream(); } else { HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol()); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(context.getUser(), context.getPassword())); HttpGet httpget = new HttpGet(xcri.toURI()); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { throw new IllegalStateException( "Invalid response [" + response.getStatusLine().getStatusCode() + "]"); } input = entity.getContent(); } } catch (MalformedURLException e) { throw new PopulatorException(e.getLocalizedMessage()); } catch (IllegalStateException e) { throw new PopulatorException(e.getLocalizedMessage()); } catch (IOException e) { throw new PopulatorException(e.getLocalizedMessage()); } catch (URISyntaxException e) { throw new PopulatorException(e.getLocalizedMessage()); } return input; }
From source file:com.k42b3.aletheia.protocol.whois.WhoisProtocol.java
protected String getTld(URL url) { int pos = url.getHost().indexOf('.'); if (pos != -1) { return url.getHost().substring(pos + 1); } else {//from w ww. j a v a2 s.c o m return url.getHost(); } }