Como fazer uma要求GET de uma API REST em Java e转换器JSON em um objeto

通用的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]

[]的

From: https://dev.to/pcollares/como-fazer-uma-requisicao-get-de-uma-api-rest-em-java-e-transformar-o-json-em-um-objeto-55ag

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值