java - API 的问题输出为空。仅来自intelliji
问题描述
我的程序有空输出。我不知道为什么。当我在 Firefox 中输入请求时,一切都很好。
我猜原因可能在输出代码中的“Array”手镯“[]”中。
public class Connect {
public String connect() {
String output = null;
try {
URL url = new URL("http://aviation-edge.com/v2/public/flights?key=[key]=3");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
output = br.readLine();
System.out.println(output);
br.close();
} catch (Exception e) {
System.out.println("Exception in WeatherApi:- " + e);
}
return output;
}
}
火狐的输出--->
[ { "geography": { "latitude": 42.3101, "longitude": -85.5977, "altitude": 9700.26, "direction": 91.15 }, "speed": { "horizontal": 920.628, "isGround": 0, "vertical": 30.42 }, "departure": { "iataCode": "ORD", "icaoCode": "ORD" }, "arrival": { "iataCode": "YYZ", "icaoCode": "YYZ" }, "aircraft": { "regNumber": "N811UA", "icaoCode": "A319", "icao24": "AB0ED6", "iataCode": "A319" }, "airline": { "iataCode": "UA", "icaoCode": "UAL" }, "flight": { "iataNumber": "UA228", "icaoNumber": "UAL228", "number": "228" }, "system": { "updated": "1558214460", "squawk": "4373" }, "status": "en-route" } ]
请帮助我累了。
解决方案
我已经修改了您的程序,请检查此代码。它现在正在工作。您错过了 while 条件。
public String connect() {
String output = null;
String key = "679820-995fb7";
try {
String connectUrlString =
"http://aviation-edge.com/v2/public/flights?key=" + key + "&limit=3";
System.out.println("URL String : " + connectUrlString);
// URL url = new URL("http://aviation-edge.com/v2/public/flights?key=[key]=3");
URL url = new URL(connectUrlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
output = response.toString();
} catch (Exception e) {
System.out.println("Exception in WeatherApi:- " + e);
}
return output;
}
推荐阅读
- google-cloud-platform - Stackdriver 日志记录 | 缺少 TraceId 和 SpanId
- amazon-web-services - AWS EC2:如何从仪表板检查磁盘大小和使用情况?
- java - 输入特定字符串后如何在java中停止while循环?
- c# - xaml/wpf TabControl 如何使用 100% 的屏幕进行拉伸
- asp.net - 如何在 ASP.NET webapp 中的服务器和客户端之间进行通信?
- android - 在 Flutter 中使用 Map 的 PageController
- javascript - Firebase电话身份验证在Vue js中不起作用
- spring-boot - Spring Boot 中的 Keycloak 管理客户端
- javascript - 来自 json 对象的多维数组
- javascript - 如何在网站上显示 wordpress 数据库表中的记录数