Panduan untuk Unirest

1. Gambaran keseluruhan

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

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

2. Persediaan Maven

Untuk memulakan, mari tambahkan kebergantungan yang diperlukan terlebih dahulu:

 com.mashape.unirest unirest-java 1.4.9 

Lihat versi terkini di sini.

3. Permintaan Ringkas

Mari hantar permintaan HTTP ringkas, 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 bahawa API fasih, cekap dan mudah dibaca.

Kami melewati tajuk dan parameter dengan API tajuk () dan medan () .

Permintaan tersebut akan dipanggil pada panggilan kaedah asJson () ; kami juga mempunyai pilihan lain di sini, seperti asBinary (), asString () dan asObject ().

Untuk melewati beberapa tajuk atau medan, kita dapat membuat peta dan meneruskannya ke .headers (Header peta) dan .field (medan 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. Lulus Param Pertanyaan

Untuk menyampaikan data sebagai String pertanyaan , kami akan menggunakan kaedah queryString () :

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

3.2. Menggunakan Parameter Laluan

Untuk melewati sebarang parameter URL, kita dapat menggunakan kaedah routeParam () :

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

Nama placeholder parameter mestilah sama dengan argumen pertama kaedah.

3.3. Permintaan Dengan Badan

Sekiranya permintaan kami memerlukan string / body JSON, kami meneruskannya menggunakan kaedah 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 menentukan pemeta objek kita. Untuk kesederhanaan, kami akan menggunakan pemeta objek Jackson.

Mari kita tambahkan kebergantungan berikut ke pom.xml :

 com.fasterxml.jackson.core jackson-databind 2.9.4 

Sentiasa gunakan versi terkini di Maven Central.

Sekarang mari kita konfigurasikan mapper kami:

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 bahawa setObjectMapper () hanya boleh dipanggil sekali, untuk menetapkan mapper; setelah contoh mapper ditetapkan, ia akan digunakan untuk semua permintaan dan respons.

Sekarang mari kita menguji fungsi baru menggunakan objek Artikel khusus :

@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. Kaedah Permintaan

Similar to any HTTP client, the framework provides separate methods for each HTTP verb:

POST:

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

PUT:

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

GET:

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

DELETE:

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

PATCH:

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

OPTIONS:

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

5. Response Methods

Once we get the response, let check the status code and status message:

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

Extract the headers:

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

Get the response body:

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

Notice that, the getRawBody(), returns a stream of the unparsed response body, whereas the getBody() returns the parsed body, using the object mapper defined in the earlier section.

6. Handling Asynchronous Requests

Unirest also has the capability to handle asynchronous requests – using java.util.concurrent.Future and callback methods:

@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, kod sumber tersedia di GitHub.