LoginSignup
0
0

RESTクライアントはこんなに簡単に作れる

Posted at

以下のライブラリが便利。

  • google-http-client
  • google-http-client-gson

Maven Repositoryを見て最新版を持ってくること。

RESTクライアントを実装する上で必要な機能

  • REST APIにHTTPでリクエストを送る
  • レスポンスが返ってくるので受け取る
  • 受け取ったレスポンスをJSONパーサで展開する

ここまでの機能がこれだけで実現できる

Main.java (一部)
HttpTransport transport = new NetHttpTransport();
Response response = transport.createRequestFactory()
        .buildGetRequest(url)
        .setParser(new JsonObjectParser(new GsonFactory()))
        .execute()
        .parseAs(Response.class);
Response.java (一部)
@Data
public class Response {
    @Key
    private Integer status;
    @Key
    private String message;
    @Key
    private Result[] results;
}

郵便番号APIを呼び出してみたサンプルが以下。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0