Tartalomjegyzék

< Java REST API kliens

Java REST API kliens - Unirest

Az Unirest-ről

Az Unirest számára minimum 11 Java szükséges. A háttérben az Apache HttpClient megvalósítást használja.

Az Unirest elérhetősége:

JAR függőségek

Ha jar fájlokat használunk a következőkre van szükség:

Maven

pom.xml
    <dependencyManagement>
  <dependencies>
      <!-- https://mvnrepository.com/artifact/com.konghq/unirest-java-bom --> 
      <dependency>
          <groupId>com.konghq</groupId>
          <artifactId>unirest-java-bom</artifactId>
          <version>4.4.0</version>
          <type>pom</type>
          <scope>import</scope>
      </dependency>
  </dependencies>
</dependencyManagement>
 
<dependencies>
    <!-- https://mvnrepository.com/artifact/com.konghq/unirest-java-core -->
    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-java-core</artifactId>
    </dependency>
 
    <!-- pick a JSON module if you want to parse JSON include one of these: -->
    <!-- Google GSON -->
    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-modules-gson</artifactId>
    </dependency>
 
    <!-- OR maybe you like Jackson better? -->
    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-modules-jackson</artifactId>
    </dependency>
</dependencies>

CRUD műveletek szinkron módban

UseUnirest.java
import kong.unirest.Unirest;
 
public class UseUnirest {
  public static void get() {
    String url = "https://jsonplaceholder.typicode.com/users";
    String res = Unirest.get(url).asString().getBody();
    System.out.println(res);    
  }
 
  public static void post() {
    String url = "https://jsonplaceholder.typicode.com/users";
    String body = "{ \"name\": \"John\", \"age\": 30 }";
    String res = Unirest.post(url)
      .header("Content-Type", "application/json")
      .body(body)
      .asString()
      .getBody();
    System.out.println(res);
  }
 
  public static void put() {
    String url = "https://jsonplaceholder.typicode.com/users/1";
    String body = "{ \"name\": \"John\", \"age\": 30 }";
    String res = Unirest.put(url)
    .header("Content-Type", "application/json")
    .body(body).asString().getBody();
    System.out.println(res);
  }
 
  public static void delete() {
    String url = "https://jsonplaceholder.typicode.com/users/1";
    String res = Unirest.delete(url).asString().getBody();
    System.out.println(res);
  }
}