Reputation: 87
Is it possible to assign string-data to a java.net.URL
?
I'm using an API who's method only accept an URL-Parameter. But i already have the content.
String content = "some text data";
URL url = createURLWithContent(content);
MyApi.handleContent( url );
the createURLWithContent()
-Method should create URL
-object that containing the data from content
, so when URL.getContent()
is called, the String (or a Stream containing the String) is returned.
I think I've seen something like this years ago.
Upvotes: 0
Views: 164
Reputation: 159096
Write the content to a file then provide a file:
URL, e.g.
public static URL createURLWithContent(String content) throws IOException {
Path tempFile = Files.createTempFile("UrlContent", null);
tempFile.toFile().deleteOnExit();
Files.writeString(tempFile, content);
return tempFile.toUri().toURL();
}
This will return a URL like this:
file:/C:/path/to/temp/UrlContent5767435257817348076.tmp
If your program is long-running, you should handle the deletion of the temporary file yourself, after the API call, rather than rely on deleteOnExit()
.
If you don't want the content on disk, you could alternatively implement your own in-memory URLStreamHandler
, and specify it when creating the URL using the URL(String protocol, String host, int port, String file, URLStreamHandler handler)
constructor. This is a lot more involved and beyond the scope of this answer.
Upvotes: 1