Networking utilities

There is a small set of basic, yet useful, networking utilities for things such as obtaining a string from a URL, downloading a file, etc.

Getting a string response from a URL

String url = "https://example.com";
String userAgent = "Example/1.0.0";
int timeout = 30_000; // 30 seconds
boolean useCaches = true; // If we request from this same URL multiple times, the response will be cached

String response = NetworkUtils.getString(url, userAgent, timeout, useCaches);
System.out.println("Response from example.com:\n" + response);

It is recommended to use the name of your mod as the first half of your user agent, and the version as the second half.

Otherwise, you can simply call getString using a URL to use the default OneConfig user agent, a timeout of 5000 milliseconds (5 seconds) and no caching.

String url = "https://example.com";

String response = NetworkUtils.getString(url);
System.out.println("Response from example.com:\n" + response);

Getting a JSON response from a URL

String url = "https://example.com";
JsonElement json = JsonUtils.parseFromUrl(url);

// You can use your JsonElement as you please

Downloading files

Again, similarly to getString, you can simply call this method with only the URL and path of the downloaded file.

Last updated