List of usage examples for java.net URL getPort
public int getPort()
From source file:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Return a URL string in which the port is always specified. *//*from w w w.ja v a 2 s. co m*/ private static String normalizeURL(String urlString) throws MalformedURLException { URL url = new URL(urlString); if (url.getPort() == -1) { return url.getProtocol() + "://" + url.getHost() + ":" + url.getDefaultPort() + url.getFile() + (url.getRef() != null ? "#" + url.getRef() : ""); } else { return urlString; } }
From source file:com.mashape.unirest.android.http.HttpClientHelper.java
private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) { Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS); if (defaultHeaders != null) { @SuppressWarnings("unchecked") Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet(); for (Entry<String, String> entry : entrySet) { request.header(entry.getKey(), entry.getValue()); }/*from w ww.ja va 2s . c o m*/ } if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) { request.header(USER_AGENT_HEADER, USER_AGENT); } if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) { request.header(ACCEPT_ENCODING_HEADER, "gzip"); } HttpRequestBase reqObj = null; String urlToRequest = null; try { URL url = new URL(request.getUrl()); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef()); urlToRequest = uri.toURL().toString(); if (url.getQuery() != null && !url.getQuery().trim().equals("")) { if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest += "?"; } urlToRequest += url.getQuery(); } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1); } } catch (Exception e) { throw new RuntimeException(e); } switch (request.getHttpMethod()) { case GET: reqObj = new HttpGet(urlToRequest); break; case POST: reqObj = new HttpPost(urlToRequest); break; case PUT: reqObj = new HttpPut(urlToRequest); break; case DELETE: //reqObj = new HttpDeleteWithBody(urlToRequest); break; case PATCH: //reqObj = new HttpPatchWithBody(urlToRequest); break; case OPTIONS: reqObj = new HttpOptions(urlToRequest); break; case HEAD: reqObj = new HttpHead(urlToRequest); break; } Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet(); for (Entry<String, List<String>> entry : entrySet) { List<String> values = entry.getValue(); if (values != null) { for (String value : values) { reqObj.addHeader(entry.getKey(), value); } } } // Set body if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) { if (request.getBody() != null) { HttpEntity entity = request.getBody().getEntity(); if (async) { if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) { reqObj.setHeader(entity.getContentType()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); entity.writeTo(output); NByteArrayEntity en = new NByteArrayEntity(output.toByteArray()); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en); } catch (IOException e) { throw new RuntimeException(e); } } else { ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } } } return reqObj; }
From source file:com.netflix.genie.web.controllers.ControllerUtils.java
/** * Given a HTTP {@code request} and a {@code path} this method will return the root of the request minus the path. * Generally the path will be derived from {@link #getRemainingPath(HttpServletRequest)} and this method will be * called subsequently.// w w w. j a va 2 s. c o m * <p> * If the request URL is {@code https://myhost/api/v3/jobs/12345/output/genie/run?myparam=4#BLAH} and the path is * {@code genie/run} this method should return {@code https://myhost/api/v3/jobs/12345/output/}. * <p> * All query parameters and references will be stripped off. * * @param request The HTTP request to get information from * @param path The path that should be removed from the end of the request URL * @return The base of the request * @throws MalformedURLException If we're unable to create a new valid URL after removing the path * @since 4.0.0 */ static URL getRequestRoot(final URL request, @Nullable final String path) throws MalformedURLException { final String currentPath = request.getPath(); final String newPath = StringUtils.removeEnd(currentPath, path); return new URL(request.getProtocol(), request.getHost(), request.getPort(), newPath); }
From source file:no.norrs.projects.andronary.utils.HttpUtil.java
public static HttpResponse GET(URL url, UsernamePasswordCredentials creds) throws IOException, URISyntaxException { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds); HttpGet httpGet = new HttpGet(url.toURI()); httpGet.addHeader("Accept", "application/json"); httpGet.addHeader("User-Agent", "Andronary/0.1"); HttpResponse response;//from w ww. ja v a 2s .c o m return httpClient.execute(httpGet); }
From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java
/** * Break apart a string into a well known address form passing back the pieces. *///from w ww. jav a 2 s . c o m private static void ParseAddressString(String addrStr, String[] hostName, String[] port, int defaultPort) { try { if ((addrStr == null) || addrStr.length() == 0) addrStr = "127.0.0.1:8080"; addrStr = addrStr.replace('/', ':'); URL url = new URL(("http://") + addrStr); if ((url.getHost() == null) && (url.getPort() == -1)) throw new IllegalArgumentException("Invalid http(s) address specified."); if ((url.getHost() == null) || (url.getHost().length() == 0)) hostName[0] = "0.0.0.0"; else hostName[0] = url.getHost(); if (url.getPort() == -1) port[0] = "" + defaultPort; else port[0] = "" + url.getPort(); } catch (MalformedURLException ex) { throw new IllegalArgumentException("Invalid http(s) address specified."); } }
From source file:davmail.http.DavGatewaySSLProtocolSocketFactory.java
/** * Register custom Socket Factory to let user accept or reject certificate *//*w ww. java2s . co m*/ public static void register() { String urlString = Settings.getProperty("davmail.url"); try { URL url = new URL(urlString); String protocol = url.getProtocol(); if ("https".equals(protocol)) { int port = url.getPort(); if (port < 0) { port = HttpsURL.DEFAULT_PORT; } Protocol.registerProtocol(url.getProtocol(), new Protocol(protocol, (ProtocolSocketFactory) new DavGatewaySSLProtocolSocketFactory(), port)); } } catch (MalformedURLException e) { DavGatewayTray.error(new BundleMessage("LOG_INVALID_URL", urlString)); } }
From source file:com.github.rnewson.couchdb.lucene.HttpClientFactory.java
public static synchronized HttpClient getInstance() throws MalformedURLException { if (instance == null) { final HttpParams params = new BasicHttpParams(); // protocol params. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(params, false); // connection params. HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setStaleCheckingEnabled(params, false); ConnManagerParams.setMaxTotalConnections(params, 1000); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1000)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 5984)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final ClientConnectionManager cm = new ShieldedClientConnManager( new ThreadSafeClientConnManager(params, schemeRegistry)); instance = new DefaultHttpClient(cm, params); if (INI != null) { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final Iterator<?> it = INI.getKeys(); while (it.hasNext()) { final String key = (String) it.next(); if (!key.startsWith("lucene.") && key.endsWith(".url")) { final URL url = new URL(INI.getString(key)); if (url.getUserInfo() != null) { credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(url.getUserInfo())); }//from w w w . ja v a2 s .com } } instance.setCredentialsProvider(credsProvider); instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(), 0); } } return instance; }
From source file:no.norrs.projects.andronary.service.utils.HttpUtil.java
public static HttpResponse GET(URL url, UsernamePasswordCredentials creds) throws IOException, URISyntaxException { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds); HttpGet httpGet = new HttpGet(url.toURI()); httpGet.addHeader("Accept", "application/json"); httpGet.addHeader("User-Agent", "Andronary/0.1"); HttpResponse response;//from w w w .j a v a2 s.c o m return httpClient.execute(httpGet); }
From source file:org.openremote.android.console.util.HTTPUtil.java
/** * Down load file and store it in local context. * /*from w ww . ja v a 2s . c om*/ * @param serverUrl the current server url * @param fileName the file name for downloading * * @return the int */ private static int downLoadFile(Context context, String serverUrl, String fileName) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpClient client = new DefaultHttpClient(params); int statusCode = ControllerException.CONTROLLER_UNAVAILABLE; try { URL uri = new URL(serverUrl); if ("https".equals(uri.getProtocol())) { Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context), uri.getPort()); client.getConnectionManager().getSchemeRegistry().register(sch); } HttpGet get = new HttpGet(serverUrl); SecurityUtil.addCredentialToHttpRequest(context, get); HttpResponse response = client.execute(get); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == Constants.HTTP_SUCCESS) { FileOutputStream fOut = context.openFileOutput(fileName, Context.MODE_PRIVATE); InputStream is = response.getEntity().getContent(); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { fOut.write(buf, 0, len); } fOut.close(); is.close(); } } catch (MalformedURLException e) { Log.e("OpenRemote-HTTPUtil", "Create URL fail:" + serverUrl); } catch (IllegalArgumentException e) { Log.e("OpenRemote-IllegalArgumentException", "Download file " + fileName + " failed with URL: " + serverUrl, e); } catch (ClientProtocolException cpe) { Log.e("OpenRemote-ClientProtocolException", "Download file " + fileName + " failed with URL: " + serverUrl, cpe); } catch (IOException ioe) { Log.e("OpenRemote-IOException", "Download file " + fileName + " failed with URL: " + serverUrl, ioe); } return statusCode; }
From source file:com.seajas.search.utilities.tags.URLTag.java
/** * Protect a given URL by starring out the password-portion. * /*from w w w . j a v a 2 s. c o m*/ * @param url * @return String */ public static String protectUrl(final String url) { try { URL actualUrl = new URL(url); return actualUrl.getProtocol() + "://" + (StringUtils.isEmpty(actualUrl.getUserInfo()) ? "" : "****@") + actualUrl.getHost() + (actualUrl.getPort() == -1 ? "" : ':' + actualUrl.getPort()) + actualUrl.getPath() + (StringUtils.isEmpty(actualUrl.getQuery()) ? "" : '?' + actualUrl.getQuery()); } catch (MalformedURLException e) { return url; } }