If you read the RFC 2397 carefully, you'll see that the "data" URL scheme is defined like that:
data:[<mediatype>][;base64],<data>
So to generate this data, you'd use something like that:
byte[] fakeImage = new byte[1];
StringBuilder sb = new StringBuilder();
// acquired from file extension
String mimeType = "image/jpg";
sb.append("data:");
sb.append(mimeType);
sb.append(";base64,");
sb.append(Base64.getEncoder().encodeToString(fakeImage));
The interesting part comes now: You'll have to register you own protocol handler, which however is well defined:
If this is the first URL object being created with the specifiedprotocol, a stream protocol handler object, an instance ofclass URLStreamHandler, is created for that protocol:
1.If the application has previously set up an instance of URLStreamHandlerFactory as the stream handler factory,then the createURLStreamHandler method of that instanceis called with the protocol string as an argument to create thestream protocol handler.
2.If no URLStreamHandlerFactory has yet been set up,or if the factory's createURLStreamHandler methodreturns null, then the constructor finds thevalue of the system property:
java.protocol.handler.pkgs
If the value of that system property is not null,it is interpreted as a list of packages separated by a verticalslash character '|'. The constructor tries to loadthe class named:
<package>.<protocol>.Handler
where <package> is replaced by the name of the packageand <protocol> is replaced by the name of the protocol.If this class does not exist, or if the class exists but it is nota subclass of URLStreamHandler, then the next packagein the list is tried.
3.If the previous step fails to find a protocol handler, then theconstructor tries to load from a system default package.
<system default package>.<protocol>.Handler
If this class does not exist, or if the class exists but it is not asubclass of URLStreamHandler, then a MalformedURLException is thrown.
So you just write the following:
String previousValue = System.getProperty("java.protocol.handler.pkgs") == null ? "" : System.getProperty("java.protocol.handler.pkgs")+"|";
System.setProperty("java.protocol.handler.pkgs", previousValue+"stackoverflow");
In order to this for work, you'll have to create a package named stackoverflow.data and within a class named Handler with the following content:
package stackoverflow.data;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
}
Then you can just create a new URL without getting any exception:
URL url = new URL(sb.toString());
I have no clue why you need it this way, but there you are.