简体   繁体   中英

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 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

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 ? System should be from capital as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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