get from api and parse

102 阅读1分钟
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class APIClient {
    public static void main(String[] args) {
        String apiEndpoint = "https://example.com/api/";
        String path = "documents/";
        String filename = "example.txt";

        try {
            URL url = new URL(apiEndpoint + path + filename);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                List<Bean> beanList = new ArrayList<>();
                boolean isDataSection = false;
                int recordCount = 0;

                while ((line = reader.readLine()) != null) {
                    if (!isDataSection) {
                        if (line.startsWith("Total")) {
                            String[] parts = line.split(" ");
                            recordCount = Integer.parseInt(parts[1]);
                            isDataSection = true;
                        }
                    } else {
                        String[] values = line.split("\\|");
                        if (values.length > 0) {
                            Bean bean = new Bean();
                            bean.setHeader1(values[0]);
                            bean.setHeader2(values[1]);
                            bean.setHeader3(values[2]);
                            bean.setHeader4(values[3]);
                            beanList.add(bean);
                        }
                    }
                }
                reader.close();

                System.out.println("Record count: " + recordCount);
                System.out.println("Bean list: " + beanList);
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class Bean {
        private String header1;
        private String header2;
        private String header3;
        private String header4;

        // Getters and setters

        @Override
        public String toString() {
            return "Bean{" +
                    "header1='" + header1 + '\'' +
                    ", header2='" + header2 + '\'' +
                    ", header3='" + header3 + '\'' +
                    ", header4='" + header4 + '\'' +
                    '}';
        }
    }
}