【问题标题】:Strange error in my java code with httpconnection我的 java 代码中带有 httpconnection 的奇怪错误
【发布时间】:2020-06-17 03:53:56
【问题描述】:

我写了这段代码:

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

感谢您的帮助

【问题讨论】:

    标签: java http http-get httpconnection openjdk-11


    【解决方案1】:

    这里有些地方不对,不是处理异常,应该是这样的:

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

    【讨论】:

    • Main.java:7: error: ')' expected final URL url = new URL(spec: "https://google.com");
    • 我试试看。它没有帮助
    • 终端提议在规范之后放置一个括号
    • 编辑了答案
    【解决方案2】:

    这段代码应该可以工作

    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 是什么?系统也应该来自资本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2013-10-05
      • 1970-01-01
      相关资源
      最近更新 更多