Answer the question
In order to leave comments, you need to log in
How to parse json using hhtpUrlConnection?
The link https://jsonplaceholder.typicode.com/posts
contains json, My task is to parse json in which an array of objects, then convert it to classes and print it. What am I doing wrong here?
the code:
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
String url = "https://jsonplaceholder.typicode.com/posts";
try {
HttpURLConnection httpClient = (HttpURLConnection) new URL(url).openConnection();
httpClient.setRequestMethod("GET");
httpClient.setRequestProperty("User", "Google Ghrome");
int responseCode = httpClient.getResponseCode();
System.out.println("URL сайта: " + url);
System.out.println("код ответа: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(httpClient.getInputStream()));
User[] users = gson.fromJson(in, User[].class);
System.out.println(users);
} catch (IOException e) {
e.printStackTrace();
}
}
Answer the question
In order to leave comments, you need to log in
Thus, I parse information from the tax database. Works great. Modify and create objects.
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question