Java – add “http: / /” before my address
I extract addresses from a source, but some extracts do not have http: / / addresses in front of them. How can I check whether the addresses have http: / / if they are not, how can I add http: / / infrant?: o
I guess this error is due to the "lack" of http: / / infrant
java.net.MalformedURLException: no protocol: www.speedtest.net at java.net.URL.<init>(URL.java:583) at java.net.URL.<init>(URL.java:480) at java.net.URL.<init>(URL.java:429) at a.PageRead.r(PageRead.java:29) at a.ThreadDownloaderWriter.run(ThreadDownloaderWriter.java:35) at java.lang.Thread.run(Thread.java:722) public StringBuilder readPage() { try { URL url = new URL(this.strURL); System.out.println(this.strURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } reader.close(); return sb; } catch (MalformedURLException e) { e.printStackTrace(); return new StringBuilder(""); } catch (IOException e) { e.printStackTrace(); return new StringBuilder(""); } }
Solution
The literal answer to your question is as follows:
String url = ... ; // Whatever if (!url.startsWith("http://")) { url = "http://" + url; }
But this is still not a good solution For example, how about HTTPS URLs? How about FTP or even file system URL (file: / /) Then you may want to consider case sensitive things ("http: / /"! = "http: / /"! = "http: / /" even if they actually mean the same thing and will be accepted through the Java URL class)
You can try to be more careful:
if (!url.toLowerCase().matches("^\\w+://.*")) { url = "http://" + url; }
This matches the beginning of the URL string with any "word character" followed by a colon (:) and two slashes (/ /), and then defaults to http: / / if the protocol part of the URL is missing This will cover more cases than the original (text) answer
Finally, if someone gives you a URL without a protocol part, it is an invalid URL
You should consider reading a book on Java programming because these are basic logic / Java API issues