如何在 Java 中處理 MalformedURLException?
在使用 Java(JSE)進行客戶端-伺服器程式設計時,如果在程式中使用 java.net.URL 類物件,則需要透過傳遞表示所需 URL 的字串來例項化此類,以便建立連線。如果傳遞的字串中的 URL 無法解析或缺少合法的協議,則會生成 MalformedURLException。
示例
在以下 Java 示例中,我們嘗試建立與頁面的連線併發布響應。
我們修改了協議部分,將其更改為 htt,而它應該是 http 或 https。
import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
String url = "ht://tutorialspoint.tw/";
URL obj = new URL(url);
//Opening a connection
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//Sending the request
conn.setRequestMethod("GET");
int response = conn.getResponseCode();
if (response == 200) {
//Reading the response to a StringBuffer
Scanner responseReader = new Scanner(conn.getInputStream());
StringBuffer buffer = new StringBuffer();
while (responseReader.hasNextLine()) {
buffer.append(responseReader.nextLine()+"
");
}
responseReader.close();
//Printing the Response
System.out.println(buffer.toString());
}
}
}執行時異常
Exception in thread "main" java.net.MalformedURLException: unknown protocol: htt at java.net.URL.<init>(Unknown Source) at java.net.URL.<init>(Unknown Source) at java.net.URL.<init>(Unknown Source) at myPackage.HttpGetExample.main(HttpGetExample.java:11)
處理 MalformedURLException
解決此問題的唯一方法是確保傳遞的 URL 是合法的,並具有正確的協議。
最好的方法是在繼續執行程式之前驗證 URL。對於驗證,可以使用正則表示式或提供 URL 驗證器的其他庫。在以下程式中,我們使用異常處理本身來驗證 URL。
示例
import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class HttpGetExample {
public static boolean isUrlValid(String url) {
try {
URL obj = new URL(url);
obj.toURI();
return true;
} catch (MalformedURLException e) {
return false;
} catch (URISyntaxException e) {
return false;
}
}
public static void main(String[] args) throws IOException {
String url = "ht://tutorialspoint.tw/";
if(isUrlValid(url)) {
URL obj = new URL(url);
//Opening a connection
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//Sending the request
conn.setRequestMethod("GET");
int response = conn.getResponseCode();
if (response == 200) {
//Reading the response to a StringBuffer
Scanner responseReader = new Scanner(conn.getInputStream());
StringBuffer buffer = new StringBuffer();
while (responseReader.hasNextLine()) {
buffer.append(responseReader.nextLine()+"
");
}
responseReader.close();
//Printing the Response
System.out.println(buffer.toString());
}
}else {
System.out.println("Enter valid URL");
}
}
}輸出
Enter valid URL
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP