Panduan untuk Unirest

1. Ikhtisar

Unirest adalah pustaka klien HTTP ringan dari Mashape. Bersama dengan Java, ini juga tersedia untuk Node.js, .Net, Python, Ruby, dll.

Sebelum kita masuk, perhatikan bahwa kita akan menggunakan mocky.io untuk semua permintaan HTTP kita di sini.

2. Pengaturan Maven

Untuk memulai, mari tambahkan dependensi yang diperlukan terlebih dahulu:

 com.mashape.unirest unirest-java 1.4.9 

Lihat versi terbaru di sini.

3. Permintaan Sederhana

Mari kirim permintaan HTTP sederhana, untuk memahami semantik kerangka kerja:

@Test public void shouldReturnStatusOkay() { HttpResponse jsonResponse = Unirest.get("//www.mocky.io/v2/5a9ce37b3100004f00ab5154") .header("accept", "application/json").queryString("apiKey", "123") .asJson(); assertNotNull(jsonResponse.getBody()); assertEquals(200, jsonResponse.getStatus()); }

Perhatikan bahwa API tersebut lancar, efisien dan cukup mudah dibaca.

Kami mengirimkan header dan parameter dengan API header () dan ladang () .

Dan permintaan dipanggil pada pemanggilan metode asJson () ; kami juga memiliki opsi lain di sini, seperti asBinary (), asString () dan asObject ().

Untuk meneruskan beberapa header atau bidang, kita dapat membuat peta dan meneruskannya ke .headers (Map headers) dan .fields (Bidang peta) masing-masing:

@Test public void shouldReturnStatusAccepted() { Map headers = new HashMap(); headers.put("accept", "application/json"); headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154"); Map fields = new HashMap(); fields.put("name", "Sam Baeldung"); fields.put("id", "PSP123"); HttpResponse jsonResponse = Unirest.put("//www.mocky.io/v2/5a9ce7853100002a00ab515e") .headers(headers).fields(fields) .asJson(); assertNotNull(jsonResponse.getBody()); assertEquals(202, jsonResponse.getStatus()); }

3.1. Meneruskan Parameter Kueri

Untuk melewatkan data sebagai String kueri , kita akan menggunakan metode queryString () :

HttpResponse jsonResponse = Unirest.get("//www.mocky.io/v2/5a9ce37b3100004f00ab5154") .queryString("apiKey", "123")

3.2. Menggunakan Path Params

Untuk meneruskan parameter URL apa pun, kita bisa menggunakan metode routeParam () :

HttpResponse jsonResponse = Unirest.get("//www.mocky.io/v2/5a9ce37b3100004f00ab5154/{userId}") .routeParam("userId", "123")

Nama tempat penampung parameter harus sama dengan argumen pertama untuk metode tersebut.

3.3. Permintaan Dengan Tubuh

Jika permintaan kami membutuhkan string / JSON body, kami meneruskannya menggunakan metode body () :

@Test public void givenRequestBodyWhenCreatedThenCorrect() { HttpResponse jsonResponse = Unirest.post("//www.mocky.io/v2/5a9ce7663100006800ab515d") .body("{\"name\":\"Sam Baeldung\", \"city\":\"viena\"}") .asJson(); assertEquals(201, jsonResponse.getStatus()); }

3.4. Pemeta Objek

Untuk menggunakan asObject () atau body () dalam permintaan, kita perlu mendefinisikan mapper objek kita. Untuk kesederhanaan, kita akan menggunakan mapper objek Jackson.

Pertama-tama, tambahkan dependensi berikut ke pom.xml :

 com.fasterxml.jackson.core jackson-databind 2.9.4 

Selalu gunakan versi terbaru di Maven Central.

Sekarang mari kita konfigurasikan mapper kita:

Unirest.setObjectMapper(new ObjectMapper() { com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); public String writeValue(Object value) { return mapper.writeValueAsString(value); } public  T readValue(String value, Class valueType) { return mapper.readValue(value, valueType); } });

Perhatikan bahwa setObjectMapper () hanya boleh dipanggil sekali, untuk menyetel mapper; setelah instance mapper disetel, itu akan digunakan untuk semua permintaan dan tanggapan.

Sekarang mari kita uji fungsionalitas baru menggunakan objek Artikel kustom :

@Test public void givenArticleWhenCreatedThenCorrect() { Article article = new Article("ID1213", "Guide to Rest", "baeldung"); HttpResponse jsonResponse = Unirest.post("//www.mocky.io/v2/5a9ce7663100006800ab515d") .body(article) .asJson(); assertEquals(201, jsonResponse.getStatus()); }

4. Metode Permintaan

Mirip dengan klien HTTP apa pun, kerangka kerja menyediakan metode terpisah untuk setiap kata kerja HTTP:

POS:

Unirest.post("//www.mocky.io/v2/5a9ce7663100006800ab515d")

TARUH:

Unirest.put("//www.mocky.io/v2/5a9ce7663100006800ab515d")

DAPATKAN:

Unirest.get("//www.mocky.io/v2/5a9ce7663100006800ab515d")

MENGHAPUS:

Unirest.delete("//www.mocky.io/v2/5a9ce7663100006800ab515d")

PATCH:

Unirest.patch("//www.mocky.io/v2/5a9ce7663100006800ab515d")

PILIHAN:

Unirest.options("//www.mocky.io/v2/5a9ce7663100006800ab515d")

5. Metode Respon

Setelah kami mendapatkan respons, periksa kode status dan pesan status:

//... jsonResponse.getStatus() //...

Ekstrak header:

//... jsonResponse.getHeaders(); //...

Dapatkan respons tubuh:

//... jsonResponse.getBody(); jsonResponse.getRawBody(); //...

Perhatikan bahwa, getRawBody (), mengembalikan aliran dari isi respons yang tidak diurai, sedangkan getBody () mengembalikan badan yang diurai, menggunakan pemeta objek yang ditentukan di bagian sebelumnya.

6. Menangani Permintaan Asynchronous

Unirest juga memiliki kemampuan untuk menangani permintaan asinkron - menggunakan metode java.util.concurrent.Future dan callback:

@Test public void whenAysncRequestShouldReturnOk() { Future
    
      future = Unirest.post( "//www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms") .header("accept", "application/json") .asJsonAsync(new Callback() { public void failed(UnirestException e) { // Do something if the request failed } public void completed(HttpResponse response) { // Do something if the request is successful } public void cancelled() { // Do something if the request is cancelled } }); assertEquals(200, future.get().getStatus()); }
    

The com.mashape.unirest.http.async.Callback interface provides three methods, failed(), cancelled() and completed().

Override the methods to perform the necessary operations depending on the response.

7. File Uploads

To upload or send a file as a part of the request, pass a java.io.File object as a field with name file:

@Test public void givenFileWhenUploadedThenCorrect() { HttpResponse jsonResponse = Unirest.post( "//www.mocky.io/v2/5a9ce7663100006800ab515d") .field("file", new File("/path/to/file")) .asJson(); assertEquals(201, jsonResponse.getStatus()); }

We can also use ByteStream:

@Test public void givenByteStreamWhenUploadedThenCorrect() { try (InputStream inputStream = new FileInputStream( new File("/path/to/file/artcile.txt"))) { byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); HttpResponse jsonResponse = Unirest.post( "//www.mocky.io/v2/5a9ce7663100006800ab515d") .field("file", bytes, "article.txt") .asJson(); assertEquals(201, jsonResponse.getStatus()); } }

Or use the input stream directly, adding the ContentType.APPLICATION_OCTET_STREAM as the second argument in the fields() method:

@Test public void givenInputStreamWhenUploadedThenCorrect() { try (InputStream inputStream = new FileInputStream( new File("/path/to/file/artcile.txt"))) { HttpResponse jsonResponse = Unirest.post( "//www.mocky.io/v2/5a9ce7663100006800ab515d") .field("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, "article.txt").asJson(); assertEquals(201, jsonResponse.getStatus()); } }

8. Unirest Configurations

The framework also supports typical configurations of an HTTP client like connection pooling, timeouts, global headers etc.

Let's set the number of connections and number maximum connections per route:

Unirest.setConcurrency(20, 5);

Configure connection and socket timeouts :

Unirest.setTimeouts(20000, 15000);

Note that the time values are in milliseconds.

Now let's set HTTP headers for all our requests:

Unirest.setDefaultHeader("X-app-name", "baeldung-unirest"); Unirest.setDefaultHeader("X-request-id", "100004f00ab5");

We can clear the global headers anytime:

Unirest.clearDefaultHeaders();

At some point, we might need to make requests through a proxy server:

Unirest.setProxy(new HttpHost("localhost", 8080));

One important aspect to be aware of is closing or exiting the application gracefully. Unirest spawns a background event loop to handle the operations, we need to shut down that loop before exiting our application:

Unirest.shutdown();

9. Conclusion

In this tutorial, we focused on the lightweight HTTP client framework – Unirest. We worked with some simple examples, both in a synchronous but also async modes.

Finally, we also used several advanced configurations – such as connection pooling, proxy settings etc.

Seperti biasa, kode sumber tersedia di GitHub.