1 /* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.io.ByteArrayInputStream; 25 import java.io.InputStream; 26 import java.net.ContentHandlerFactory; 27 import java.net.URL; 28 import java.net.URLConnection; 29 import java.net.URLStreamHandler; 30 import java.net.URLStreamHandlerFactory; 31 32 public class Test { 33 34 public static void main(String[] args) throws Exception { 35 if (args.length > 0) { 36 String fqn = args[0]; 37 38 @SuppressWarnings("unchecked") 39 Class<? extends ContentHandlerFactory> c = 40 (Class<? extends ContentHandlerFactory>) Class.forName(fqn); 41 42 ContentHandlerFactory f = c.newInstance(); 43 44 URLConnection.setContentHandlerFactory(f); 45 } 46 47 // One does not simply use a ContentHandler... 48 // From an end user perspective ContentHandler is used indirectly 49 // and it's more like SPI rather than API. So there's a certain amount 50 // of preparations needs to be done beforehand. 51 52 URLStreamHandlerFactory streamHandlerFactory = 53 (protocol) -> 54 new URLStreamHandler() { 55 @Override 56 protected URLConnection openConnection(URL u) { 57 return newUrlConnection(u); 58 } 59 }; 60 61 URL.setURLStreamHandlerFactory(streamHandlerFactory); 62 63 // Finally 64 Object content = new URL("whatever:").getContent(); 65 66 System.out.println("Content class is: " + content.getClass()); 67 } 68 69 private static URLConnection newUrlConnection(URL u) { 70 return new URLConnection(u) { 71 @Override public void connect() { } 72 73 @Override 74 public InputStream getInputStream() { return null; } 75 76 @Override public String getContentType() { return "text/plain"; } 77 }; 78 } 79 }