Java URL Tutorial and Examples.
1. Get Host From a String url
We’ll wrap it in a try catch block so as to catch MalformedURLException
.
public static String getHost(String urlstr){
try {
URL u = new URL(urlstr);
String ret=u.getProtocol()+"://"+u.getHost();
return ret;
} catch (MalformedURLException e) {
return "";
}
}
2. Get Host Without Protocol
public static String getHostOnly(String urlstr){
try {
URL u = new URL(urlstr);
String ret=u.getHost();
return ret;
} catch (MalformedURLException e) {
return "";
}
}
3. Add Query Map
public static String addQueryMap(HashMap<String, String> queryMap, String url) {
Iterator iter = queryMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
try {
String q = (String) entry.getValue();
String e = URLEncoder.encode(q, "utf-8");
url += "&" + entry.getKey() + "=" + e;
} catch (Exception e) {
e.printStackTrace();
}
}
return url;
}
4. Get Query String From HashMap
public static String getQueryString(HashMap<String, String> queryMap) {
String url = "";
Iterator iter = queryMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
try {
String q = (String) entry.getValue();
String e = URLEncoder.encode(q, "utf-8");
url += "&" + entry.getKey() + "=" + e;
} catch (Exception e) {
e.printStackTrace();
}
}
return url;
}
5. Get query String From a List
public static String getQueryString(List<NameValuePair> queryMap) {
String url = "";
for(NameValuePair p:queryMap){
try {
String q = p.getValue();
if(q!=null&&!q.equals("")) {
String e = URLEncoder.encode(q, "utf-8");
url += "&" + p.getName() + "=" + e;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return url;
}
6. Encode strings
public static String encode(String w, String s) {
try {
return URLEncoder.encode(w,s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
7. How to Validate a URL
public static boolean isValideUrl(String url) {
if(url==null){
return false;
}
if(url.startsWith("http://")||url.startsWith("https://")){
return true;
}
return false;
}
8. Open Web Browser in any OS
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
/**
* Simple class to open a web browser in another process.
*
* @author Douglas Lau
* @author Michael Darter
*/
public class WebBrowser {
/** Exception for web browser not found */
static private final IOException BROWSER_NOT_FOUND =
new FileNotFoundException("Could not find web browser");
/** Linux web browsers */
static private final String[] LINUX_BROWSERS = {
"firefox", "chrome", "chromium", "mozilla", "epiphany", "opera"
};
/** Execute a subprocess with a web browser at the given URL */
static public void open(URL url) throws IOException {
if (url != null)
open(url.toString());
}
/** Open a URL in a web browser */
static public void open(String url) throws IOException {
String osName = System.getProperty("os.name");
if (osName.startsWith("Mac OS"))
openMac(url);
else if (osName.startsWith("Windows"))
openWindows(url);
else
openLinux(url);
}
/** Open a web browser on a Mac computer */
static private void openMac(String url) throws IOException {
try {
Class<?> mgr = Class.forName(
"com.apple.eio.FileManager");
Method openURL = mgr.getDeclaredMethod("openURL",
new Class[] { String.class }
);
openURL.invoke(null, new Object[] { url });
}
catch (ClassNotFoundException e) {
throw BROWSER_NOT_FOUND;
}
catch (NoSuchMethodException e) {
throw BROWSER_NOT_FOUND;
}
catch (IllegalAccessException e) {
throw BROWSER_NOT_FOUND;
}
catch (InvocationTargetException e) {
throw BROWSER_NOT_FOUND;
}
}
/** Open a web browser on a Windows computer */
static private void openWindows(String url) throws IOException {
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
}
/** Open a web browser on a Linux computer */
static private void openLinux(String url) throws IOException {
String browser = locateBrowser();
Runtime.getRuntime().exec(new String[] {
browser, url
});
}
/** Locate a browser on a Linux computer */
static private String locateBrowser() throws IOException {
for (String browser: LINUX_BROWSERS) {
if (browserExists(browser))
return browser;
}
throw BROWSER_NOT_FOUND;
}
/** Check if a browser exists */
static private boolean browserExists(String name) throws IOException {
Process p = Runtime.getRuntime().exec(
new String[] { "which", name }
);
try {
return p.waitFor() == 0;
}
catch (InterruptedException e) {
return false;
}
}
}