简体   繁体   English

我的带有 httpconnection 的 java 代码中的奇怪错误

[英]Strange error in my java code with httpconnection

I write this code:我写这个代码:

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

And get this error:并得到这个错误:

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

I work with OpenJdk:我使用 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)

and UBUNTU 18.04和 UBUNTU 18.04

Thanks for any help谢谢你的帮助

A few things are wrong here, not handling exception, it should rather be something like this:这里有几件事是错误的,不是处理异常,而是应该是这样的:

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

This code should work这段代码应该可以工作

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

I don't understand what is 'spec:' IDE hint or smth ?我不明白什么是 'spec:' IDE 提示或 smth ? System should be from capital as well.制度也应该来自资本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM