通用的UM简易API REST的可替代性JSON的通用要求GET。
Google的参考书目(Nossaúnicadependênciaserá),在Java上以JSON和JSON形式存在。
帕拉nosso exemplo伊礼obter OS dados德aeronaves disponibilizados陈健波庵serviçogratuito,邻开放天空 ,一个documentação德SUA API颇得SER encontrada褐: https://opensky-network.org/apidoc/rest.html
Primeiramente vamos criar uma classe com os mesmos campos e tepos da resposta JSON da API queseráconsultada:
Dados.java
public class Dados {
private String time;
private String[][] states;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String[][] getStates() {
return states;
}
public void setStates(String[][] states) {
this.states = states;
}
}
Agora,nossa classe负责人,要求提供HTTP数据,并定义BufferedReader。
Depois simplesmente passo oconteúdoJSON,在GSON上,不存在“ Dados”。
Main.java
public class APIRest {
public static void main(String[] args) {
try {
String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
System.out.println("Erro " + conn.getResponseCode() + " ao obter dados da URL " + url);
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output = "";
String line;
while ((line = br.readLine()) != null) {
output += line;
}
conn.disconnect();
Gson gson = new Gson();
Dados dados = gson.fromJson(new String(output.getBytes()), Dados.class);
System.out.println("TIME: " + dados.getTime());
System.out.println("STATES: " + Arrays.toString(dados.getStates()[0]));
} catch (IOException ex) {
Logger.getLogger(APIRest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Saídaseráalgo assim:
TIME: 1559738039
STATES: [3c6671, DLH1153 , Germany, 1559738039, 1559738039, 6.6706, 46.3694, 10363.2, false, 259.33, 5.24, 0.33, null, 10599.42, 5507, false, 0]
[]的