[[oktatas:programozás:java:java_rest_api_kliens|< Java REST API kliens]]
====== Java REST API Gson használat ======
* **Szerző:** Sallai András
* Copyright (c) 2022, Sallai András
* Szerkesztve: 2022, 2023
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Bevezetés =====
Ebben a példában **Gson** könyvtárat a és a Java **HttpURLConnection** osztályát használjuk a REST API elérésére.
A Gson beszerzése:
* https://github.com/google/gson (2022)
===== JSON tartalom =====
Legyen egy JSON tartalom, amit valamilyen REST API-val kiszolgálunk. Lehet például Node.js csomag: json-server vagy hai-server.
{
"employees": [
{
"id": 1,
"name": "Nagy János",
"city": "Szolnok",
"salary": 8400000
},
{
"id": 2,
"name": "Páros Lajos",
"city": "Szeged",
"salary": 3430000
},
{
"id": 3,
"name": "Aranyos Enikő",
"city": "Szolnok",
"salary": 4245000
}
]
}
===== Dolgozók lekérése =====
public class Employee {
String name;
String city;
double salary;
public Employee() {}
public Employee(String name, String city, double salary) {
this.name = name;
this.city = city;
this.salary = salary;
}
}
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class HttpClient {
public String getData(String urlStr) {
String text = null;
try {
text = tryGetData(urlStr);
} catch (IOException e) {
System.err.println("Hiba! A lekérés sikertelen!");
System.err.println(e.getMessage());
}
return text;
}
public String tryGetData(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.connect();
String text = null;
int responseCode = http.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("Http válasz: " + responseCode);
}else {
text = new String(
http.getInputStream().readAllBytes(),
StandardCharsets.UTF_8);
}
return text;
}
public ArrayList getEmployees() {
String urlStr = "http://[::1]:8000/employees";
String text = this.getData(urlStr);
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
Employee[] employeeArray = gson.fromJson(text, Employee[].class);
ArrayList list = new ArrayList<>(Arrays.asList(employeeArray));
return list;
}
}
import java.util.ArrayList;
public class Client {
public void printEmps() {
System.out.println("REST API lekérés");
HttpClient http = new HttpClient();
ArrayList list = http.getEmployees();
for(Employee employee: list) {
System.out.println(employee.name);
}
}
}
public class App {
public static void main(String[] args) throws Exception {
new Client().printEmps();;
}
}
===== Token küldése =====
URL url = new URL("http://localhost:8000/api/valami");
String token = "as3klaj334lkdfj";
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization","Bearer " + token);
con.setRequestProperty("Content-Type","application/json");
con.setRequestMethod("POST");
===== Példa projekt =====
* https://github.com/oktat/exjclient.git