我想在我的程序中使用响应代码 请告诉我以下代码中的错误
public class Main{
public static void main(String args[]) throws Exception {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
}
}
答案 0 :(得分:2)
public class Main{
public static void main(String args[]) throws Exception {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
}
}
答案 1 :(得分:1)
错误很明显。
openConnection()
是URL
类的一种方法,在您的班级中未定义。您必须使用之前创建的URL类对象。
调用openConnection()方法必须是这样的 -
url.openConnection()
它返回一个URLConnection
对象,您必须将此对象强制转换为HttpURLConnection
。
答案 2 :(得分:0)
原因是编译器告诉类构造函数(URL)和方法(openConnection
..)抛出异常(在signatures
中定义)并采取一些必要的步骤。
您有两个选择:
Throw
来自主方法的已检查异常。
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " +
httpCon.getResponseCode());
}
或
使用Exception
try catch block.
public static void main(String[] args) {
URL url;
HttpURLConnection httpCon;
try {
url = new URL("http://www.google.com");
httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
答案 3 :(得分:0)
你忘了放url
将其更改为HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
package naveed.workingfiles;
import java.net.HttpURLConnection;
import java.net.URL;
public class Url {
public static void main(String args[]) throws Exception {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
}
}
答案 4 :(得分:0)
尝试将对象强制转换为HttpURLConnection
public class Main{
public static void main(String args[]) throws Exception {
URL url = new URL("http://www.google.com");
//Cast the object to HttpURLConnection
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
}
}