我是JAVA的新手,刚刚学会了它的基础知识,现在我正在尝试学习一些提前JAVA,我不知道它的进步与否,但我想要做的是当我点击搜索按钮时我将发送1个http呼叫,当我删除http请求代码或当我删除搜索按钮代码然后它单独工作但不在一起
这是我的代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package google;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author user
*/
public class Google extends JFrame {
private final String USER_AGENT = "Mozilla/5.0";
public Google() {
initUI();
}
private void callUrl() throws Exception {
String url = "http://www.google.com/search?q=mkyong";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
private void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton searchButton = new JButton("Search");
searchButton.setBounds(50, 60, 80, 30);
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
callUrl();
}
});
panel.add(searchButton);
setTitle("Search");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Google ex = new Google();
ex.setVisible(true);
}
});
}
}
很抱歉,如果这个问题已经存在,我搜索了很多,但没有得到正确的解决方案。 感谢
错误:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.Exception; must be caught or declared to be thrown
at google.Google$1.actionPerformed(Google.java:70)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
答案 0 :(得分:2)
这不是特定于你的问题,但它将帮助你理解java中的异常处理。
有两种类型的例外
应该在代码中处理已检查的异常,这意味着您需要在方法中处理或抛出异常,以便方法的调用者可以小心。
要捕获异常,您需要使用try
和catch
。如果您不想处理异常,可以将方法声明为throws SomeException
,以便调用者可以处理。
例如:
public String getContentsOfFile(String filePath) {
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
String contents = //convert stream to string and return
return contents;
} catch(FileNotFoundException e){
//Here this method is interested in handling the checked exception.
}
return null;
}
如果您不想处理异常(使您的方法抛出异常)
public String getContentsOfFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
String contents = //convert stream to string and return
return contents;
}
另一个最佳实践是,您可以捕获已检查的异常并抛出未经检查的异常(RuntimeException
),以便该方法的调用者不需要处理该异常。 Spring广泛使用这种方法。
try {
.....
} catch (FileNotFoundException fne) {
//log fne
throw new RuntimeException(fne);
}
以下是关于何时选择已检查的例外以及何时选择未经检查的例外的问题。 When to choose checked and unchecked exceptions
答案 1 :(得分:1)
下面的链接说openconnection方法可以抛出异常。
如果您使用此方法,则必须使用catch或再次抛出它。
http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URL.html#openConnection%28%29
编辑:不要抛出异常,请尝试这样
private void callUrl() {
try {
// your stuff
} catch (Exception e) {
// print it for sure
}
}
答案 2 :(得分:1)
我将您的代码剪切并粘贴到Eclipse中,它让我(通过突出显示错误)尝试了以下内容:
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
callUrl();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
答案 3 :(得分:1)
HttpURLConnection#openConnection抛出一个异常,callUrl()声明。 initUI()调用callUrl()但不声明异常。这可能会有所帮助:
private void initUI() throws Exception {
或者,您可以使用try / catch块包围HttpURLConnection#openConnection()调用:
private void callUrl() throws Exception {
String url = "http://www.google.com/search?q=mkyong";
URL obj = new URL(url);
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
// handle the failed connection cleanly...
}
// and then continue processing
答案 4 :(得分:1)
由于您不熟悉Java,我建议使用Eclipse(IDE)编辑代码。它会自动为您提供建议。
在searchButton actionListener“actionPerformed”调用中,您需要按如下方式编辑代码:
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
try {
callUrl();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
我所做的只是添加一个try / catch处理程序,因为你已经将“callUrl()”函数声明为抛出异常。我使用您粘贴的代码运行上面的代码 - 这很有效。
如果您需要进一步的帮助,请告诉我。
答案 5 :(得分:0)
这是您的错误:
private void callUrl() throws Exception {
当你说某个方法抛出Exception
时,每个调用者都必须以某种方式处理该异常。几乎没有必要说一个方法抛出Exception
(它是所有“已检查”异常的母亲)与一些更精确的条件,特别是如果该方法只抛出“未经检查”的异常( Error或RuntimeException的子类)然后根本不需要使用throws
子句。
在上面的例子中,你似乎有一些IOException的可能性,这意味着你需要捕获或声明它们,但它应该足以说throws IOException
vs throws Exception
,或者,更好,{ {1}}方法内部的IOException并处理它。 (最好处理异常,尽可能接近抛出它的上下文。)
提示:对于测试用例或“快速而肮脏”的程序,在catch
方法上说throws WhateverException
就足够了,而不必在那里处理它。 (对于任何“真正的”应用程序,当然,您应该捕获异常并提供格式良好的错误消息。)
(你可以感谢Goodenough先生所有这些混乱。)