Unirestのガイド
1概要
UnirestはMashapeの軽量HTTPクライアントライブラリです。 Javaと一緒に、Node.js、.Net、Python、Rubyなどにも利用可能です。
ここに入る前に、ここでのすべてのHTTPリクエストにはhttps://www.mocky.io/[mocky.io]を使用します。
2 Mavenのセットアップ
まずはじめに、必要な依存関係を追加しましょう。
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
here
をチェックしてください。 。
3簡単なリクエスト
フレームワークのセマンティクスを理解するために、単純なHTTPリクエストを送信しましょう。
@Test
public void shouldReturnStatusOkay() {
HttpResponse<JsonNode> jsonResponse
= Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154")
.header("accept", "application/json").queryString("apiKey", "123")
.asJson();
assertNotNull(jsonResponse.getBody());
assertEquals(200, jsonResponse.getStatus());
}
APIは流暢で、効率的で、そしてとても読みやすいです。
header()
および
fields()
APIを使用してヘッダーとパラメーターを渡します。
そして、リクエストは
asJson()
メソッド呼び出しで呼び出されます。ここには、
asBinary()、asString()
、__asObject()などの他のオプションもあります。
複数のヘッダーまたはフィールドを渡すには、マップを作成してそれぞれ
.headers(Map <String、Object>ヘッダー)
および
.fields(Map <String、String>フィールド)
に渡します。
@Test
public void shouldReturnStatusAccepted() {
Map<String, String> headers = new HashMap<>();
headers.put("accept", "application/json");
headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154");
Map<String, Object> fields = new HashMap<>();
fields.put("name", "Sam Baeldung");
fields.put("id", "PSP123");
HttpResponse<JsonNode> jsonResponse
= Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e")
.headers(headers).fields(fields)
.asJson();
assertNotNull(jsonResponse.getBody());
assertEquals(202, jsonResponse.getStatus());
}
3.1. クエリパラメータを渡す
データをクエリ
Stringとして渡すには、
queryString()__メソッドを使用します。
HttpResponse<JsonNode> jsonResponse
= Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154")
.queryString("apiKey", "123")
3.2. パスパラメータの使用
URLパラメータを渡すには、
routeParam()
メソッドを使用できます。
HttpResponse<JsonNode> jsonResponse
= Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154/{userId}")
.routeParam("userId", "123")
パラメータプレースホルダ名は、メソッドの最初の引数と同じである必要があります。
3.3. ボディとの要求
リクエストに文字列/JSON本文が必要な場合は、
body()
メソッドを使用して渡します。
@Test
public void givenRequestBodyWhenCreatedThenCorrect() {
HttpResponse<JsonNode> jsonResponse
= Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
.body("{\"name\":\"Sam Baeldung\", \"city\":\"viena\"}")
.asJson();
assertEquals(201, jsonResponse.getStatus());
}
3.4. オブジェクトマッパー
リクエストで
asObject()
または
body()
を使用するには、オブジェクトマッパーを定義する必要があります。簡単にするために、Jacksonオブジェクトマッパーを使用します。
まず、
pom.xml
に次の依存関係を追加しましょう。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
それでは、マッパーを設定しましょう。
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> T readValue(String value, Class<T> valueType) {
return mapper.readValue(value, valueType);
}
});
マッパーを設定するために、
setObjectMapper()
を1回だけ呼び出すようにしてください。マッパーインスタンスが設定されると、それはすべてのリクエストとレスポンスに使用されます。
カスタム
Article
オブジェクトを使って新しい機能をテストしましょう。
@Test
public void givenArticleWhenCreatedThenCorrect() {
Article article
= new Article("ID1213", "Guide to Rest", "baeldung");
HttpResponse<JsonNode> jsonResponse
= Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
.body(article)
.asJson();
assertEquals(201, jsonResponse.getStatus());
}
4リクエスト方法
他のHTTPクライアントと同様に、フレームワークはHTTP動詞ごとに別々のメソッドを提供します。
役職:
Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
プット:
Unirest.put("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
取得する:
Unirest.get("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
DELETE:
Unirest.delete("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
パッチ:
Unirest.patch("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
オプション:
Unirest.options("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
5対応方法
応答があったら、ステータスコードとステータスメッセージを確認しましょう。
----//...
jsonResponse.getStatus()
//...
----
ヘッダを抽出します。
----//...
jsonResponse.getHeaders();//...
----
レスポンスボディを取得します:
----//...
jsonResponse.getBody();
jsonResponse.getRawBody();//...
----
getRawBody()、
は解析されていないレスポンスボディのストリームを返すのに対し、
getBody()
は前のセクションで定義したオブジェクトマッパーを使って解析されたボディを返します。
6. 非同期リクエストの処理
Unirestには、
java.util.concurrent.Future
とコールバックメソッドを使用して、非同期リクエストを処理する機能もあります。
@Test
public void whenAysncRequestShouldReturnOk() {
Future<HttpResponse<JsonNode>> future = Unirest.post(
"http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms")
.header("accept", "application/json")
.asJsonAsync(new Callback<JsonNode>() {
public void failed(UnirestException e) {
//Do something if the request failed
}
public void completed(HttpResponse<JsonNode> response) {
//Do something if the request is successful
}
public void cancelled() {
//Do something if the request is cancelled
}
});
assertEquals(200, future.get().getStatus());
}
com.mashape.unirest.http.async.Callback <T>
インターフェースは3つのメソッド、
failed()
、
cancelled()
、および__completed()を提供します。
応答に応じて必要な操作を実行するためにメソッドをオーバーライドします。
7. ファイルのアップロード
リクエストの一部としてファイルをアップロードまたは送信するには、
java.io.File
オブジェクトをfileという名前のフィールドとして渡します。
@Test
public void givenFileWhenUploadedThenCorrect() {
HttpResponse<JsonNode> jsonResponse = Unirest.post(
"http://www.mocky.io/v2/5a9ce7663100006800ab515d")
.field("file", new File("/path/to/file"))
.asJson();
assertEquals(201, jsonResponse.getStatus());
}
__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<JsonNode> jsonResponse = Unirest.post(
"http://www.mocky.io/v2/5a9ce7663100006800ab515d")
.field("file", bytes, "article.txt")
.asJson();
assertEquals(201, jsonResponse.getStatus());
}
}
または、
fields()
メソッドの2番目の引数として
ContentType.APPLICATION
OCTET
STREAM
を追加して、入力ストリームを直接使用します。
@Test
public void givenInputStreamWhenUploadedThenCorrect() {
try (InputStream inputStream = new FileInputStream(
new File("/path/to/file/artcile.txt"))) {
HttpResponse<JsonNode> jsonResponse = Unirest.post(
"http://www.mocky.io/v2/5a9ce7663100006800ab515d")
.field("file", inputStream, ContentType.APPLICATION__OCTET__STREAM, "article.txt").asJson();
assertEquals(201, jsonResponse.getStatus());
}
}
8 unirest設定
このフレームワークは、コネクションプーリング、タイムアウト、グローバルヘッダなどのHTTPクライアントの典型的な設定もサポートします
ルートごとの接続数と最大接続数を設定しましょう。
Unirest.setConcurrency(20, 5);
接続とソケットのタイムアウトを設定します。
Unirest.setTimeouts(20000, 15000);
時間の値はミリ秒単位です。
それでは、すべてのリクエストにHTTPヘッダーを設定しましょう。
Unirest.setDefaultHeader("X-app-name", "baeldung-unirest");
Unirest.setDefaultHeader("X-request-id", "100004f00ab5");
グローバルヘッダはいつでも消去できます。
Unirest.clearDefaultHeaders();
ある時点で、プロキシサーバーを介して要求を出す必要があるかもしれません。
Unirest.setProxy(new HttpHost("localhost", 8080));
注意しなければならない重要な点は、アプリケーションを適切に閉じるか終了することです。 Unirestは操作を処理するためにバックグラウンドイベントループを生成します、アプリケーションを終了する前にそのループをシャットダウンする必要があります。
Unirest.shutdown();
9結論
このチュートリアルでは、軽量HTTPクライアントフレームワーク – Unirestに焦点を当てました。いくつかの簡単な例を、同期モードと非同期モードの両方で使用しました。
最後に、接続プーリング、プロキシ設定など、いくつかの高度な設定も使用しました。
いつものように、ソースコードはhttps://github.com/eugenp/tutorials/tree/master/libraries[over GitHub]から入手できます。