我在 stackoverflow 上找不到问题的解决方案。可能是我长得不好,如果是这样的话我真的很抱歉。
<小时/>无论如何,关于问题: 我制作了自己的浏览器,如果 URL 不存在或没有响应,我希望它给用户一个错误。我在 Java Swing 中使用以下命令: EditorPane = setPage(url)//其中 EditorPane 是 JEditorPane
<小时/>SetPage(URL url) 仅当参数中发送的不是 url 时才会出现错误。那么,如果 URL 没有响应,我如何获得反馈?
<小时/>预先感谢您,- 朱利安 ps:评论是瑞典语的,但不是很有帮助!
private void loadPage(URL url, boolean AddOrNot) {
try{
System.out.println("loadPage Try");
displayEditorPane.setPage(url); // setter sidan till url
//URL newUrl = displayEditorPane.getPage(); //ger den nuvarande sidans url funkar ei
//displayEditorPane.setPage(newUrl); //get error ?!?
String hist=url.toString();
textField.setText(hist); // men denna fungerar
if(AddOrNot){//lägger till url i history-list om du inte använt back / forward knapp
history.add(hist);
JMenuItem historyFile = new JMenuItem(hist);
historyFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textField.setText(hist);
position=0;
Launch(true);
}
});
HistoryMenu.add(historyFile);
}
//** kollar om forward och back knapparna ska vara aktiva **//
if(position!=history.size()-1){
BackButton.setEnabled(true);
}else{
BackButton.setEnabled(false);
}
if(position>0){
ForwardButton.setEnabled(true);
}else{
ForwardButton.setEnabled(false);
}
}catch(IOException io ){
System.out.println("loadPage Catch " + io);
msgError("Unable to open page");
}
}
最佳答案
displayEditorPane.setPage(url);
如果您需要有关加载和成功的更高级反馈,则有必要放弃这种简单的方法,而采用应用程序所在的更复杂的方法。控制阅读内容。为此,请查看 URLConnection
和 HttpURLConnection
。具体方法:
-
URLConnection.getInputStream()
:Returns an input stream that reads from this open connection. A
SocketTimeoutException
can be thrown when reading from the returned input stream if the read timeout expires before data is available for read. HttpURLConnection.getResponseCode()
:Gets the status code from an HTTP response message. For example, in the case of the following status lines:
HTTP/1.0 200 OK HTTP/1.0 401 Unauthorized
It will return
200
and401
respectively. Returns-1
if no code can be discerned from the response (i.e., the response is not valid HTTP).
有关处理流的信息,请参阅 Basic I/O本教程的类(class)。
关于Java Swing Web 浏览器如何注意到 URL 不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27459738/