• Как спарсить json используя hhtpUrlConnection?

    Max_LiVi
    @Max_LiVi
    Java-разработчик
    Таким образом я парсю информацию из бд налоговой. Отлично работает. Переделай и создавай объекты.
    public static HashMap <String,String> sendRequestByContractorInformation (String request){
            HashMap <String,String> contractorInfo = new HashMap<>();
            final String KEY = "ключ";
            String URL = "https://api-fns.ru/api/egr?req=".concat(request).concat("&key=").concat(KEY);
            final String METHOD = "GET";
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(URL).openConnection();
                connection.setRequestMethod(METHOD);
                connection.connect();
                JSONObject jsonObject;
                int status = connection.getResponseCode();
                if (status == HttpURLConnection.HTTP_OK) {
                    InputStream in = connection.getInputStream();
                    jsonObject = new JSONObject(IOUtils.toString(in)); // здесь получаем JSON
                    JSONArray jsonArrayItems = (JSONArray) jsonObject.get("items");
                    Iterator jsonArrayItemsIterator = jsonArrayItems.iterator();
                    while (jsonArrayItemsIterator.hasNext()){
                        JSONObject element = (JSONObject) jsonArrayItemsIterator.next();
                        System.out.println(element);
                        if (element.has("ЮЛ")){ // проверяем, есть ли JSON c нужным ключом и делаем с ним, то что нам надо!!!
                            System.out.println("JSON с ключом <ЮЛ> присутствует");
                            JSONObject jsonObjectUL = new JSONObject(element.getJSONObject("ЮЛ").toString());
                            System.out.println(jsonObjectUL);
                            if (jsonObjectUL.has(CONTRACTOR_INFO.FULL_NAME.getValue())){
                                System.out.println("JSON с ключом <"+CONTRACTOR_INFO.FULL_NAME.getValue()+"> присутствует");
                                contractorInfo.put(CONTRACTOR_INFO.FULL_NAME.name(),jsonObjectUL.getString(CONTRACTOR_INFO.FULL_NAME.getValue()));
                            } else {
                                System.out.println("JSON с ключом <"+CONTRACTOR_INFO.FULL_NAME.getValue()+"> ОТСУТСТВУЕТ!!!");
                                contractorInfo.put(CONTRACTOR_INFO.FULL_NAME.name(),"Нет данных");
                            }
                            System.out.println("Добавлена запись: " + (CONTRACTOR_INFO.FULL_NAME.name() + "=" + contractorInfo.get(CONTRACTOR_INFO.FULL_NAME.name())));
                        }
                    }
                    in.close();
                    connection.disconnect();
                } else {
                    System.out.println("Соединение с сервером не установлено... Попробуйте повторить операцию позднее.");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return contractorInfo;
        }
    Ответ написан
    Комментировать