LoginSignup
88
85

More than 5 years have passed since last update.

Retrofitを試してみる

Last updated at Posted at 2014-01-28

注意: この記事はRetrofit 1を対象に書かれています。現在はRetrofit 2がリリースされておりますので内容的に古いです。また、サンプルで利用したYouTube GData APIはサービスを終了していますので動きません。ストックしてくださる方がまだいらっしゃるのでいずれ更新したいと思いますm(_ _)m

調べ物をしていたらたまたまRetrofitというRESTライブラリを見つけたので使ってみました。(okHttpというSPDY対応のライブラリも面白そうなんで後日試してみる予定)

とりあえずYouTubeのGData APIから動画の検索結果を持ってくる実装を作ってみました。

ソースはGitHubにうpしてます。
https://github.com/tsuyosh/RetrofitExamples

YouTube GData APIにアクセスするために以下の様なインターフェースを作ります。引数にキーワードとソート設定と開始位置(1から始まる)を渡すとYouTube動画の検索結果(Feed)がかえってくる仕組みです。
@GET@QueryはRetrofitのアノテーションです。大体の意味はわかると思います。他にも@Path, @POST, @Body, @FormUrlEncoded, @Multipart, @Field, @Headers, @HeaderがRetrofitには用意されています。

public interface YouTubeDataService {
    @GET("/feeds/api/videos?max-results=20&v=2")
    public Feed search(@Query("q") String query,
            @Query("orderby") String orderBy,
            @Query("start-index") int startIndex);
}

呼び出し元はこんな感じです。RestAdapterがYouTubeDataServiceの実装を生成してくれます。

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setServer("http://gdata.youtube.com")
                .setConverter(new SimpleXMLConverter())
                .build();
        restAdapter.setLogLevel(LogLevel.FULL); // デバッグ用
        YouTubeDataService service = restAdapter
                .create(YouTubeDataService.class);

        Feed result = service.search(query, "published", 1);

GDataのレスポンスはXML(Atom)ですがこれをPOJOに変換(デシリアライズ)するにはConverterの設定が必要です。

今回はRetrofitのリポジトリに入っているSimpleXMLConverterを使いました。SimpleXMLConverterは別途Simpleが必要です。

追記

Simpleに付属しているxtaxやxpp3のjarファイルも一緒にlibsに入れてしまうとapkが作れないのでsimplexmlのみlibsに入れてください。

ちなみにbuild.gradleでは以下のように記述

build.gradle
compile('org.simpleframework:simple-xml:2.7.+'){
    exclude module: 'stax'
    exclude module: 'stax-api'
    exclude module: 'xpp3'
}

88
85
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
88
85