List of usage examples for java.net URLConnection getContentType
public String getContentType()
From source file:com.netsteadfast.greenstep.util.FSUtils.java
/** * get MIME-TYPE /*from w ww.ja v a2 s .co m*/ * Using java.net.URL * * @param file * @return * @throws Exception */ public static String getMimeType4URL(File file) throws IOException, MalformedURLException, Exception { String mimeType = ""; if (file == null || !file.exists() || file.isDirectory()) { return mimeType; } URL url = new URL(file.getPath()); URLConnection urlConnection = url.openConnection(); mimeType = urlConnection.getContentType(); return mimeType; }
From source file:org.apache.synapse.config.Util.java
/** * Get an object from a given URL. Will first fetch the content from the * URL and depending on the content-type, a suitable XMLToObjectMapper * (if available) would be used to transform this content into an Object. * If a suitable XMLToObjectMapper cannot be found, the content would be * treated as XML and an OMNode would be returned * @param url the URL to the resource/*from www . ja va2 s . co m*/ * @return an Object created from the given URL */ public static Object getObject(URL url) { try { URLConnection urlc = url.openConnection(); XMLToObjectMapper xmlToObject = getXmlToObjectMapper(urlc.getContentType()); try { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(urlc.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement omElem = builder.getDocumentElement(); // detach from URL connection and keep in memory // TODO remove this omElem.build(); if (xmlToObject != null) { return xmlToObject.getObjectFromOMNode(omElem); } else { return omElem; } } catch (XMLStreamException e) { log.warn("Content at URL : " + url + " is non XML.."); return urlc.getContent(); } } catch (IOException e) { handleException("Error connecting to URL : " + url, e); } return null; }
From source file:com.agc.tmdb.Util.URLFetcher.java
/** * Used to get the Character Set./*www . j a v a 2 s .c o m*/ * @param URLConnection * @return */ private static Charset getCharset(URLConnection connectionObject) { Charset charset = null; String contentType = connectionObject.getContentType(); if (contentType != null) { Matcher m = Pattern.compile("harset *=[ '\"]*([^ ;'\"]+)[ ;'\"]*").matcher(contentType); if (m.find()) { String encoding = m.group(1); try { charset = Charset.forName(encoding); } catch (UnsupportedCharsetException e) { } } } if (charset == null) { charset = Charset.defaultCharset(); } return charset; }
From source file:fr.free.movierenamer.utils.URIRequest.java
private static Reader getReaderNoSync(URLConnection connection) throws IOException { Charset charset = getCharset(connection.getContentType()); return new InputStreamReader(getInputStreamNoSync(connection), charset); }
From source file:org.castafiore.utils.ResourceUtil.java
public static byte[] readUrlBinary(String url) throws Exception { URL u = new URL(url); URLConnection uc = u.openConnection(); String contentType = uc.getContentType(); int contentLength = uc.getContentLength(); if (contentType.startsWith("text/") || contentLength == -1) { throw new IOException("This is not a binary file."); }/*from w w w .jav a 2 s . c o m*/ InputStream raw = uc.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; int offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) break; offset += bytesRead; } in.close(); if (offset != contentLength) { throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes"); } return data; }
From source file:com.moviejukebox.themoviedb.tools.WebBrowser.java
private static Charset getCharset(URLConnection cnx) { Charset charset = null;/*from w w w . j av a 2 s. co m*/ // content type will be string like "text/html; charset=UTF-8" or "text/html" String contentType = cnx.getContentType(); if (contentType != null) { // changed 'charset' to 'harset' in regexp because some sites send 'Charset' Matcher m = Pattern.compile("harset *=[ '\"]*([^ ;'\"]+)[ ;'\"]*").matcher(contentType); if (m.find()) { String encoding = m.group(1); try { charset = Charset.forName(encoding); } catch (UnsupportedCharsetException e) { // there will be used default charset } } } if (charset == null) { charset = Charset.defaultCharset(); } return charset; }
From source file:com.moviejukebox.tools.WebBrowser.java
private static Charset getCharset(URLConnection cnx) { Charset charset = null;/* w w w.ja v a 2s.co m*/ // content type will be string like "text/html; charset=UTF-8" or "text/html" String contentType = cnx.getContentType(); if (contentType != null) { // changed 'charset' to 'harset' in regexp because some sites send 'Charset' Matcher m = Pattern.compile("harset *=[ '\"]*([^ ;'\"]+)[ ;'\"]*").matcher(contentType); if (m.find()) { String encoding = m.group(1); try { charset = Charset.forName(encoding); } catch (UnsupportedCharsetException error) { // there will be used default charset } } } if (charset == null) { charset = Charset.defaultCharset(); } return charset; }
From source file:org.grycap.gpf4med.util.URLUtils.java
/** * Reads data from a URL and writes them to a local file. * @param source Source URL./*w w w . j ava 2s . c om*/ * @param destination Destination file. * @throws IOException If an input/output error occurs. */ public static void download(final URL source, final File destination) throws IOException { checkArgument(source != null, "Uninitialized source"); checkArgument(destination != null, "Uninitialized destination"); final URLConnection conn = source.openConnection(); checkState(conn != null, "Cannot open connection to: " + source.toString()); final String contentType = conn.getContentType(); final int contentLength = conn.getContentLength(); checkState(StringUtils.isNotEmpty(contentType), "Cannot determine the content type of: " + source.toString()); if (contentType.startsWith("text/") || contentLength == -1) { URLUtils.downloadText(source, destination); } else { URLUtils.downloadBinary(conn, destination); } }
From source file:de.unigoettingen.sub.commons.util.stream.StreamUtils.java
/************************************************************************************ * get MimeType as {@link String} from given URL including proxy details * // ww w . j a v a 2s .c o m * @param url the url from where to get the MimeType * @param httpproxyhost host of proxy * @param httpproxyport port of proxy * @param httpproxyusername username for proxy * @param httpproxypassword password for proxy * @return MimeType as {@link String} * @throws IOException ************************************************************************************/ public static String getMimeTypeFromUrl(URL url, String httpproxyhost, String httpproxyport, String httpproxyusername, String httpproxypassword) throws IOException { if (httpproxyhost != null) { Properties properties = System.getProperties(); properties.put("http.proxyHost", httpproxyhost); if (httpproxyport != null) { properties.put("http.proxyPort", httpproxyport); } else { properties.put("http.proxyPort", "80"); } } URLConnection con = url.openConnection(); if (httpproxyusername != null) { String login = httpproxyusername + ":" + httpproxypassword; String encodedLogin = new String(Base64.encodeBase64(login.getBytes())); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin); } return con.getContentType(); }
From source file:org.openhab.io.multimedia.actions.Audio.java
@ActionDoc(text = "plays an audio stream from an url") static public synchronized void playStream( @ParamDoc(name = "url", text = "the url of the audio stream") String url) { if (streamPlayer != null) { // if we are already playing a stream, stop it first streamPlayer.close();//from w w w .j a v a 2 s . c o m streamPlayer = null; } if (url == null) { // the call was only for stopping the currently playing stream return; } try { if (url.toLowerCase().endsWith(".m3u")) { InputStream is = new URL(url).openStream(); String urls = IOUtils.toString(is); for (String line : urls.split("\n")) { if (!line.isEmpty() && !line.startsWith("#")) { url = line; break; } } } else if (url.toLowerCase().endsWith(".pls")) { InputStream is = new URL(url).openStream(); String urls = IOUtils.toString(is); for (String line : urls.split("\n")) { if (!line.isEmpty() && line.startsWith("File")) { Matcher matcher = plsStreamPattern.matcher(line); if (matcher.find()) { url = matcher.group(1); break; } } } } URL streamUrl = new URL(url); URLConnection connection = streamUrl.openConnection(); InputStream is = null; if (connection.getContentType().equals("unknown/unknown")) { //Java does not parse non-standard headers used by SHOUTCast int port = streamUrl.getPort() > 0 ? streamUrl.getPort() : 80; // Manipulate User-Agent to receive a stream shoutCastSocket = new Socket(streamUrl.getHost(), port); OutputStream os = shoutCastSocket.getOutputStream(); String user_agent = "WinampMPEG/5.09"; String req = "GET / HTTP/1.0\r\nuser-agent: " + user_agent + "\r\nIcy-MetaData: 1\r\nConnection: keep-alive\r\n\r\n"; os.write(req.getBytes()); is = shoutCastSocket.getInputStream(); } else { is = streamUrl.openStream(); } if (is != null) { Player player = new Player(is); streamPlayer = player; playInThread(player); } } catch (JavaLayerException e) { logger.error("Cannot play stream '{}': JavaLayerException - {}", url, e.getMessage()); } catch (MalformedURLException e) { logger.error("Cannot play stream '{}': MalformedURLException - {}", url, e.getMessage()); } catch (IOException e) { logger.error("Cannot play stream '{}': {}", url, e); } }