What I'm looking for specifically is some code in Java that will take a Map
object and convert it into a query string that I can append to a URL I return. I'm sure there's a library that does this and much more, but I can't find it with a quick Google search. Anyone know of one that will do this?
When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com : try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL. openConnection(); myURLConnection.
URL getQuery() method in Java with Examples The getQuery() function is a part of URL class. The function getQuery() returns the Query of a specified URL. Return Type: The function returns String Type Query of a specified URL.
Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.
The java. net. URL class represents a URL and has a complete set of methods to manipulate URL in Java.
I found apache httpcomponents to be a solid and versatile library for dealing with HTTP in Java. However, here's a sample class, which might suffice for building URL query strings:
import java.net.URLEncoder;
public class QueryString {
private String query = "";
public QueryString(HashMap<String, String> map) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
query += URLEncoder.encode(pairs.getKey(), "utf-8") + "=" +
URLEncoder.encode(pairs.getValue(), "utf-8");
if (it.hasNext()) { query += "&"; }
}
}
public QueryString(Object name, Object value) {
query = URLEncoder.encode(name.toString(), "utf-8") + "=" +
URLEncoder.encode(value.toString(), "utf-8");
}
public QueryString() { query = ""; }
public synchronized void add(Object name, Object value) {
if (!query.trim().equals("")) query += "&";
query += URLEncoder.encode(name.toString(), "utf-8") + "=" +
URLEncoder.encode(value.toString(), "utf-8");
}
public String toString() { return query; }
}
Usage:
HashMap<String, String> map = new HashMap<String, String>();
map.put("hello", "world");
map.put("lang", "en");
QueryString q = new QueryString(map);
System.out.println(q);
// => "hello=world&lang=en"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With