WebUtil is an object utility that provides simple methods for fetching data from the internet, including JSON, strings, and file downloads.
Accessing WebUtil
Configuration
Logging
Enable or disable logging for WebUtil operations:Fetching Data
fetchJSON
Fetch and parse JSON data from a URL.- Kotlin
- Java
url: String- The URL to fetch JSON from
JsonHolder - A JsonHolder object containing the parsed JSON data
Notes:
- Spaces in URLs are automatically escaped to
%20 - Returns a valid JsonHolder even if the request fails (check for error states)
- Uses Mozilla user agent for compatibility
fetchString
Fetch the content of a web page as a string.url: String- The URL to fetch
String? - The page content, or "Failed to fetch" if the request fails
Features:
- Automatically escapes spaces in URLs
- Uses default system charset for decoding
- 15-second connection and read timeout
downloadToFile
Download a file from the internet and save it to disk.url: String- The URL of the file to downloadfile: File- The destination file pathuserAgent: String- User agent string to use for the request
IOException - If the download fails
Features:
- Buffered reading and writing for efficiency
- Customizable user agent
- 1024-byte buffer size for optimal performance
Object Reference
Common Use Cases
Fetching API Data
Downloading Resources
Async Web Requests
Parsing HTML Content
Fetching with Error Handling
Downloading with Progress
Notes
- WebUtil automatically handles URL encoding for spaces
- All methods use a 15-second timeout for connections
- The default user agent is “Mozilla/4.76 (Essential)”
- Failed fetch operations print errors to console when
LOGis enabled fetchStringreturns"Failed to fetch"on error rather than throwing exceptions- Always check return values for error conditions
- For production use, consider adding retry logic for network requests