LoginSignup
21
25

More than 5 years have passed since last update.

Retrofit ver2.0.0の使い方

Last updated at Posted at 2016-02-01

Retrofit ver2.0.0の使い方

Qiita APIを例に説明します。

前提条件

レスポンスのJSONはGSONで扱う

使い方

1. 導入

gradleでインストールする。

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:latest.release'

gsonをgradleでインストールする。

compile 'com.google.code.gson:gson:2.3.1'
compile 'org.glassfish:javax.annotation:10.0-b28'

2. レスポンスのJSONをgsonに変換し、レスポンスを扱うファイルを作成
下記、サイトでレスポンスのJSONをGSONに変換し、コピペする
JSONからGSON変換サイト

QiitaGsonResponse.java
@Generated("org.jsonschema2pojo")
public class QiitaGsonResponse {

    @SerializedName("rendered_body")
    @Expose
    private String renderedBody;
    @SerializedName("body")
    @Expose
    private String body;
    @SerializedName("coediting")
    @Expose
    private Boolean coediting;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("private")
    @Expose
    private Boolean _private;
    @SerializedName("tags")
    @Expose
    private List<Tag> tags = new ArrayList<Tag>();
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("user")
    @Expose
    private User user;

    /**
     *
     * @return
     * The renderedBody
     */
    public String getRenderedBody() {
        return renderedBody;
    }

    /**
     *
     * @param renderedBody
     * The rendered_body
     */
    public void setRenderedBody(String renderedBody) {
        this.renderedBody = renderedBody;
    }

    /**
     *
     * @return
     * The body
     */
    public String getBody() {
        return body;
    }

    /**
     *
     * @param body
     * The body
     */
    public void setBody(String body) {
        this.body = body;
    }

    /**
     *
     * @return
     * The coediting
     */
    public Boolean getCoediting() {
        return coediting;
    }

    /**
     *
     * @param coediting
     * The coediting
     */
    public void setCoediting(Boolean coediting) {
        this.coediting = coediting;
    }

    /**
     *
     * @return
     * The createdAt
     */
    public String getCreatedAt() {
        return createdAt;
    }

    /**
     *
     * @param createdAt
     * The created_at
     */
    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The _private
     */
    public Boolean getPrivate() {
        return _private;
    }

    /**
     *
     * @param _private
     * The private
     */
    public void setPrivate(Boolean _private) {
        this._private = _private;
    }

    /**
     *
     * @return
     * The tags
     */
    public List<Tag> getTags() {
        return tags;
    }

    /**
     *
     * @param tags
     * The tags
     */
    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    /**
     *
     * @return
     * The title
     */
    public String getTitle() {
        return title;
    }

    /**
     *
     * @param title
     * The title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     *
     * @return
     * The updatedAt
     */
    public String getUpdatedAt() {
        return updatedAt;
    }

    /**
     *
     * @param updatedAt
     * The updated_at
     */
    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    /**
     *
     * @return
     * The url
     */
    public String getUrl() {
        return url;
    }

    /**
     *
     * @param url
     * The url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     *
     * @return
     * The user
     */
    public User getUser() {
        return user;
    }

    /**
     *
     * @param user
     * The user
     */
    public void setUser(User user) {
        this.user = user;
    }

}

3. QiitaAPIの設定
インターフェースを作成し、ベースを作る
methodがGETならアノテーションで@GET
エンドポイントをGETの()の中に設定
URLにパラメータをつける場合はQueryアノテーションをつけて仮引数を設定
Call(ジェネリクス)にする。
CallはRetrofitの型。
その中にレスポンスの型を設定する

QiitaApiService.java
/**
 * Created by hanasjima on 2016/01/28.
 */
public interface QiitaApiService {
    @GET("/api/v2/items")
    Call<List<QiitaGsonResponse>> getData(@Query("page") String page, @Query ("per_page") String per_page, @Query("query") String query);
}

4. 使い方
APIのベースURLとGSONを使うことを設定しretrofit変数を設定
どのAPIを使うかをクラス名を渡してqiitaApiserviceを設定
CallでどのAPIのメソッドを使うかを設定
非同期でAPIの結果を取得したい場合はenqueueで行う。
コールバックメソッドを指定して、結果を扱う。

ちなみに同期で取得したい場合はexecute()で行う

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //QiitaApiの使用
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://qiita.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        QiitaApiService qiitaApiservice = retrofit.create(QiitaApiService.class);
        Call<List<QiitaGsonResponse>> call = qiitaApiservice.getData("1", "20", "android");
        try {
                call.enqueue(new Callback<List<QiitaGsonResponse>>() {
                    @Override
                    public void onResponse(Response<List<QiitaGsonResponse>> response) {
                        String title = response.body().get(0).getTitle();
                        Log.d("Qiita",title);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        Log.d("Qiita", "error");
                    }
                });
        } catch (Exception e) {
            Log.d("Qiita", "レスポンスエラー");
        }
    }

参考リンク

公式

21
25
1

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
21
25