-1

我希望我的程序中的响应代码请告诉我以下代码中的错误是什么

  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());
     }
    }
4

5 回答 5

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());
 }
}
于 2013-10-04T09:06:13.190 回答
1

错误是显而易见的人。

openConnection()是类的方法,URL未在您的类中定义。您必须使用之前创建的 URL 类的对象。

调用 openConnection() 方法必须是这样的 -

url.openConnection()它返回一个URLConnection对象,您必须将此对象类型转换为HttpURLConnection.

于 2013-10-04T09:13:03.633 回答
0

原因是编译器告诉类构造函数(URL)和方法(openConnection..)抛出异常(在它们中定义signatures)并采取一些必要的步骤。

您有 2 个选项:

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();
        }
    }
于 2013-10-04T09:07:02.607 回答
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());
    }
}
于 2013-10-04T09:08:05.330 回答
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());
 }
}
于 2013-10-04T09:09:13.713 回答