Skip to content

Instantly share code, notes, and snippets.

@agershun
Created September 12, 2018 04:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save agershun/b0de66a6cb86ea69b65a72ae06ebfcd1 to your computer and use it in GitHub Desktop.
Save agershun/b0de66a6cb86ea69b65a72ae06ebfcd1 to your computer and use it in GitHub Desktop.
Пример программы на языке Java, использующей Naviaddress API
import java.util.List;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import com.google.gson.Gson;
public class Jnavi {
public static void main(String[] args) {
try {
// Подготавливаем запрос
URL url = new URL("https://staging-api.naviaddress.com/api/v1.5/Addresses/7/0022");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// Устанавливаем параметры запроса
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "application/json");
// Получаем ответ в буфер
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer stringBuffer = new StringBuffer();
// Добавляем данные из буфера в строку
while ((inputLine = in.readLine()) != null) {
stringBuffer.append(inputLine);
}
in.close();
// Ответ получен
String jsonString = stringBuffer.toString();
// Печать результатов
System.out.println(jsonString);
// Для преобразования JSON воспользуемся пакетом Gson
// (https://github.com/google/gson)
// Надо будет загрузить gson.jar в каталог приложения
// https://search.maven.org/artifact/com.google.code.gson/gson/2.8.5/jar
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
System.out.println(response.toString());
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
class Response {
public Result result;
public String toString() {
return result.toString();
}
}
class Result {
public String description;
public String container;
public String naviaddress;
public List<CoverImage> cover;
public String toString() {
String s = "Address:";
s += "[" + container + "]" + naviaddress + " - " + description + "\n";
s += "Images:\n";
for(int i=0;i<cover.size();i++) {
s += Integer.toString(i)+": "+cover.get(i).toString() + "\n";
}
return s;
}
}
class CoverImage {
public String image;
public String toString() {
return image;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment