如何在java中对json路由执行GET请求
我正试图打印此json如何在java中对json路由执行GET请求,java,Java,我正试图打印此jsonhttps://coderbyte.com/api/challenges/json/rest-get-simple,但我收到一个运行时错误 这是我的以下代码: import java.util.*; import java.io.*; import java.net.*; class Main { public static void main (String[] args) { System.setProperty("http.agent&
https://coderbyte.com/api/challenges/json/rest-get-simple
,但我收到一个运行时错误
这是我的以下代码:
import java.util.*;
import java.io.*;
import java.net.*;
class Main {
public static void main (String[] args) {
System.setProperty("http.agent", "Chrome");
try {
URL url = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple");
try {
URLConnection connection = url.openConnection();
connection.setRequestMethod("GET");
String line = "";
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder response = new StringBuilder();
while((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
System.out.println("Response: " + response.toString());
System.out.println(inputStream);
} catch (IOException ioEx) {
System.out.println(ioEx);
}
} catch (MalformedURLException malEx) {
System.out.println(malEx);
}
}
}
错误:
output logs will appear here
Main.java:12: error: cannot find symbol
connection.setRequestMethod("GET");
^
symbol: method setRequestMethod(String)
location: variable connection of type URLConnection
1 error
Main.java:12: error: cannot find symbol
connection.setRequestMethod("GET");
^
symbol: method setRequestMethod(String)
location: variable connection of type URLConnection
Main.java:15: error: incompatible types: InputStream cannot be converted to Reader
BufferedReader bufferedReader = new BufferedReader(inputStream);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors
我只想将跑步、编码、露营等爱好打印为输出。
setRequestMethod
是HttpURLConnection的成员,而不是URLConnection
对于您的特定情况,该行是可选的,可以删除。见:
您还需要包装输入流(一旦修复了第一个错误,就会遇到此错误):
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(inputStream))代码>
上述更改基于Java 11。如果您在运行时遇到异常时能够通过某种方式获得更多信息就好了。像一些异常信息,可以引导您找到解决方案。。。嗯@JoachimSauer请检查更新的问题:)