List of usage examples for java.net URL getPort
public int getPort()
From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java
public synchronized static InputStream doPost(String urlstring, String queryString, String separator, Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException { System.err.println("posting to: " + urlstring + ". query string: " + queryString); HashMap<String, String> query = parseQueryString(queryString, separator); HttpClient client = getClient();/*from ww w .jav a2 s .c om*/ URL url = new URL(urlstring); int port = url.getPort(); if (port == -1) { if (url.getProtocol().equalsIgnoreCase("http")) { port = 80; } if (url.getProtocol().equalsIgnoreCase("https")) { port = 443; } } client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol()); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); final PostMethod post = new PostMethod(url.getFile()); addHeaders(additionalHeaders, post); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); post.setRequestHeader("Accept", "*/*"); // Prepare login parameters NameValuePair[] valuePairs = new NameValuePair[query.size()]; int counter = 0; for (String key : query.keySet()) { //System.out.println("Adding pair: "+key+": "+query.get(key)); valuePairs[counter++] = new NameValuePair(key, query.get(key)); } post.setRequestBody(valuePairs); //authpost.setRequestEntity(new StringRequestEntity(requestEntity)); client.executeMethod(post); int statuscode = post.getStatusCode(); InputStream toret = null; if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = post.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } } else { System.out.println("Invalid redirect"); System.exit(1); } } else { charsetb.append(post.getResponseCharSet()); final InputStream in = post.getResponseBodyAsStream(); toret = new InputStream() { @Override public int read() throws IOException { return in.read(); } @Override public void close() { post.releaseConnection(); } }; } return toret; }
From source file:HttpTransactionUtils.java
/** * Format a base URL string ( protocol://server[:port][/file-specification] ) * /*from w w w . java2 s . c om*/ * @param url * URL to format * @param preserveFile * Keep the /directory/filename portion of the URL? * @return URL string */ public static String formatUrl(URL url, boolean preserveFile) throws MalformedURLException { StringBuilder result; int port; result = new StringBuilder(url.getProtocol()); result.append("://"); result.append(url.getHost()); if ((port = url.getPort()) != -1) { result.append(":"); result.append(String.valueOf(port)); } if (preserveFile) { String file = url.getFile(); if (file != null) { result.append(file); } } return result.toString(); }
From source file:com.fujitsu.dc.test.utils.Http.java
static Socket createSocket(URL url) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException { String host = url.getHost();/*from w w w.j a va 2 s. co m*/ int port = url.getPort(); String proto = url.getProtocol(); if (port < 0) { if ("https".equals(proto)) { port = PORT_HTTPS; } if ("http".equals(proto)) { port = PORT_HTTP; } } log.debug("sock: " + host + ":" + port); log.debug("proto: " + proto); // HTTPS?????????????SSLSocket??? if ("https".equals(proto)) { KeyManager[] km = null; TrustManager[] tm = { new javax.net.ssl.X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkClientTrusted"); } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkServerTrusted"); } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(km, tm, new SecureRandom()); SocketFactory sf = sslContext.getSocketFactory(); return (SSLSocket) sf.createSocket(host, port); } // HTTPS???????? return new Socket(host, port); }
From source file:org.cerberus.engine.execution.impl.SeleniumServerService.java
private static void getIPOfNode(TestCaseExecution tCExecution) { try {/*from w w w. ja v a 2s . c o m*/ Session session = tCExecution.getSession(); HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()) .getCommandExecutor(); SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId(); String hostName = ce.getAddressOfRemoteServer().getHost(); int port = ce.getAddressOfRemoteServer().getPort(); HttpHost host = new HttpHost(hostName, port); HttpClient client = HttpClientBuilder.create().build(); URL sessionURL = new URL("http://" + session.getHost() + ":" + session.getPort() + "/grid/api/testsession?session=" + sessionId); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, r); if (!response.getStatusLine().toString().contains("403")) { InputStream contents = response.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(contents, writer, "UTF8"); JSONObject object = new JSONObject(writer.toString()); URL myURL = new URL(object.getString("proxyId")); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { tCExecution.setIp(myURL.getHost()); tCExecution.setPort(String.valueOf(myURL.getPort())); } } } catch (IOException ex) { LOG.error(ex.toString()); } catch (JSONException ex) { LOG.error(ex.toString()); } }
From source file:eu.trentorise.smartcampus.network.RemoteConnector.java
private static String normalizeURL(String uriString) throws RemoteException { try {// w w w . j a v a2s . c om URL url = new URL(uriString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); uriString = uri.toURL().toString(); } catch (Exception e) { throw new RemoteException(e.getMessage()); } return uriString; }
From source file:app.web.Application2ITCase.java
public static URL toLocationPath(String location) { try {//ww w.j a v a 2 s.c om URL fullUrl = new URL(location); // We just throw the query string if any return new URL(fullUrl.getProtocol(), fullUrl.getHost(), fullUrl.getPort(), fullUrl.getPath()); } catch (MalformedURLException e) { throw new RuntimeException(e); } }
From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java
public static String getApplicationId(HttpServletRequest request) throws MalformedURLException { StringBuffer appID = new StringBuffer(); URL url = new URL(request.getRequestURL().toString()); appID.append(url.getProtocol()).append("://").append(url.getHost()); /*if (! (url.getProtocol().equalsIgnoreCase("http") && (url.getPort() == 80 || url.getPort() <= 0)) || ! ( url.getProtocol().equalsIgnoreCase("https") && (url.getPort() == 443 || url.getPort() <= 0)) ) { appID.append(':').append(url.getPort()); }*///from w ww. java2 s.co m if (url.getPort() > 0) { appID.append(':').append(url.getPort()); } return appID.toString(); }
From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java
/** * Check the http state cookies to see if we have the proper session id cookie * * @param reqUrl URL being requested/*from www .ja va 2s . c om*/ * @param state HTTP state object * @param basePath base path of requests * * @return true if a cookie matching the basePath, server host and port, and request protocol and appropriate * session cookie name is found */ public static boolean hasSessionCookie(final URL reqUrl, final HttpState state, final String basePath) { final CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); final Cookie[] initcookies = cookiespec.match(reqUrl.getHost(), reqUrl.getPort() > 0 ? reqUrl.getPort() : 80, basePath.endsWith("/") ? basePath : basePath + "/", HTTP_SECURE_PROTOCOL.equalsIgnoreCase(reqUrl.getProtocol()), state.getCookies()); boolean hasSession = false; if (initcookies.length == 0) { hasSession = false; } else { for (final Cookie cookie : initcookies) { if (JAVA_SESSION_COOKIE_NAME.equals(cookie.getName()) || JAVA_SESSION_COOKIE_PATTERN.matcher(cookie.getName()).matches()) { logger.debug("Saw session cookie: " + cookie.getName()); hasSession = true; break; } } } return hasSession; }
From source file:gr.wavesoft.webng.io.web.WebStreams.java
public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException { try {//from w w w. j ava 2 s.com // WebRequest connection ClientConnectionRequest connRequest = connectionManager.requestConnection( new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null); ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS); try { // Prepare request BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath()); // Setup headers if (headers != null) { for (String k : headers.keySet()) { request.addHeader(k, headers.get(k)); } } // Send request conn.sendRequestHeader(request); // Fetch response HttpResponse response = conn.receiveResponseHeader(); conn.receiveResponseEntity(response); HttpEntity entity = response.getEntity(); if (entity != null) { BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true); // Replace entity response.setEntity(managedEntity); } // Do something useful with the response // The connection will be released automatically // as soon as the response content has been consumed return response; } catch (IOException ex) { // Abort connection upon an I/O error. conn.abortConnection(); throw ex; } } catch (HttpException ex) { throw new IOException("HTTP Exception occured", ex); } catch (InterruptedException ex) { throw new IOException("InterruptedException", ex); } catch (ConnectionPoolTimeoutException ex) { throw new IOException("ConnectionPoolTimeoutException", ex); } }
From source file:org.wso2.carbon.appfactory.apiManager.integration.utils.Utils.java
public static HttpPost createHttpPostRequest(URL url, List<NameValuePair> params, String path) throws AppFactoryException { URI uri;// ww w . j a va 2 s . c o m try { uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), path, URLEncodedUtils.format(params, "UTF-8"), null); } catch (URISyntaxException e) { String msg = "Invalid URL syntax"; log.error(msg, e); throw new AppFactoryException(msg, e); } return new HttpPost(uri); }