我写的代码是:
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
感谢您的帮助
此代码应能在中工作
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?系统也应该来自资本。
这里有一些错误,没有处理异常,应该是这样的:
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);
}
}