Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Created February 8, 2023 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasG77/4de8f0a39142d45fc51cdf70cb0fdc63 to your computer and use it in GitHub Desktop.
Save ThomasG77/4de8f0a39142d45fc51cdf70cb0fdc63 to your computer and use it in GitHub Desktop.
Java basic http client API Geo (Java 11+)
package com.demo.HttpClientDemo;
// Package Jar issue de https://github.com/stleary/JSON-java
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.net.http.HttpClient; // < New in Java 11, can also handle HTTP/2 requests!
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/**
* Hello API Découpage Administratif!
*
*/
public class App
{
public static void main( String[] args )
{
String url = "https://geo.api.gouv.fr/communes?nom=Montpellier";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
try {
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(App::parse)
.join();
} catch(Exception e) {
System.out.println("ERROR!");
System.out.println(e);
}
}
public static String parse(String responseBody) {
JSONArray communes = new JSONArray(responseBody);
try {
for (int i = 0; i < communes.length(); i++) {
JSONObject commune = communes.getJSONObject(i);
String nom = commune.getString("nom");
String code = commune.getString("code");
String codeDepartement = commune.getString("codeDepartement");
String siren = commune.getString("siren");
String codeEpci = commune.getString("codeEpci");
int population = commune.getInt("population");
System.out.println("Nom: " + nom);
System.out.println("Code: " + code);
System.out.println("Code du département: " + codeDepartement);
System.out.println("Code SIREN: " + siren);
System.out.println("Code de l'EPCI: " + codeEpci);
System.out.println("Population: " + population);
System.out.println("---");
}
} catch(Exception e){
System.out.println(e);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment