0

我写了这段代码:

import java.net.HttpURLConnection;
import java.net.URL;
public class Main{
        private static HttpURLConnection connection;
        public static void main(String[] args){
                final URL url = new URL (spec: "https://google.com");
                connection = (HttpURLConnection) url.openConnection();
                connection =url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                int status = connection.getResponseCode();
                system.out.println(status);
        }
}

并得到这个错误:

Main.java:8: error: ')' expected

我使用 OpenJdk:

openjdk version "11.0.6" 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1, mixed mode, sharing)

和 Ubuntu 18.04

谢谢你的帮助

4

2 回答 2

0

这里有几件事是错误的,不处理异常,应该是这样的:

public class Main {
        private static HttpURLConnection connection;
        public static void main(String[] args) throws Exception {
                final URL url = new URL("https://google.com");
                connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                int status = connection.getResponseCode();
                System.out.println(status);
        }
}
于 2020-03-04T15:46:57.237 回答
0

这段代码应该可以工作

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main{
  private static HttpURLConnection connection;
  public static void main(String[] args) throws IOException {
    final URL url = new URL("https://google.com");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);
    int status = connection.getResponseCode();
    System.out.println(status);
  }
}

我不明白 'spec:' IDE 提示或 smth 是什么?系统也应该来自资本。

于 2020-03-04T16:01:25.890 回答