How to Build a Robust GET Parameter Builder with Java URL Encoding
This article walks through improving a Java GET‑parameter concatenation utility by overloading methods, handling Chinese characters with java.net.URLEncoder, and providing reusable code for converting JSON or Map arguments into properly encoded query strings for HttpClient requests.
The author needed a reliable way to assemble GET request URLs and initially used a simple string‑replace approach; after encountering illegal Chinese characters, the method was refactored to automatically apply URL encoding using Java's built‑in URLEncoder.
An overloaded getHttpGet method is introduced. If the args object is null or empty, the method delegates to a simple version that returns new HttpGet(url). Otherwise it calls changeJsonToArguments(args) to turn the JSON payload into a query string, removes any spaces, and creates the final HttpGet instance.
The helper changeJsonToArguments(JSONObject argument) iterates over each key in the JSON object, encodes the corresponding value with urlEncoderText, and then builds the query string by converting the whole JSON to a string, stripping the surrounding braces, replacing commas with &, colons with =, and deleting quotation marks. The resulting string starts with a leading ? and is returned.
An alternative overload for Map<String, String> is also provided. It creates a StringBuffer initialized with ?, appends each key=value& pair after encoding the value, and finally removes the trailing ampersand to accommodate empty cases.
The low‑level encoder urlEncoderText(String text) wraps java.net.URLEncoder.encode(text, "utf-8") in a try‑catch block, printing "Data format error!" if an UnsupportedEncodingException occurs, and returns the encoded result.
Together, these snippets demonstrate a step‑by‑step process for safely constructing GET URLs that work with both ASCII and non‑ASCII characters, making the utility reusable across different API‑testing scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
