27
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Retrofit を使ってAPIを呼びだす

Last updated at Posted at 2017-12-16

AndroidのライブラリであるHTTPクライアント「Retrofit」を使ってWeb APIを呼び出す。

#呼び出すもの
Zaif APIでビットコインのティッカー情報
http://techbureau-api-document.readthedocs.io/ja/latest/public/2_individual/4_ticker.html
#準備

build.gradle
dependencies {
  ....
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
}

GSONはJSONデータをJavaオブジェクトに変換するものでGoogleが開発した(だからGSON?)

#インターフェイス

API_Interface.java
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface API_Interface {

    @GET("/api/1/ticker/{currency_pair}")
    Call<Data> API(@Path("currency_pair") String currency_pair);
}

アノテーションで使えるものはGET、POST、PUT、DELETE、HEADの5つ。
@GET()内はベースURLの後のURLを指定、{}と@Path()内は同じ文字列にすること。そして型を後置の文で指定している。
#Dataクラス

Data.java
public class Data {
    public float last;
    public float high;
    public float low;
    public float volume;
    public float bid;
    public float ask;

    public Data(float last, float high, float low, float volume, float bid, float ask) {
        super();
        this.last = last;
        this.high = high;
        this.low = low;
        this.volume = volume;
        this.bid = bid;
        this.ask = ask;
    }

    public float getLast() {
        return last;
    }

    public float getHigh() {
        return high;
    }

    public float getLow() {
        return low;
    }

    public float getVolume() {
        return volume;
    }

    public float getBid() {
        return bid;
    }

    public float getAsk() {
        return ask;
    }
}

変数名を戻り値と一緒にすることでデータを突っ込んでくれる。
#アクティビティ

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

        final TextView text_last=(TextView)findViewById(R.id.text_last);
        final TextView text_high=(TextView)findViewById(R.id.text_high);
        final TextView text_low=(TextView)findViewById(R.id.text_low);
        final TextView text_volume=(TextView)findViewById(R.id.text_volume);
        final TextView text_bid=(TextView)findViewById(R.id.text_bid);
        final TextView text_ask=(TextView)findViewById(R.id.text_ask);
        
        Retrofit retro = new Retrofit.Builder()
                .baseUrl("https://api.zaif.jp")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        
        API_Interface service = retro.create(API_Interface.class);
        
        Call<Data> btc = service.API("btc_jpy");
        
        btc.enqueue(new Callback<Data>() {
            @Override
            public void onResponse(Call<Data> call, Response<Data> response) {
                Data ticker = response.body();
                text_last.setText("Last:"+Float.toString(ticker.getLast())+"円");
                text_high.setText("High:"+Float.toString(ticker.getHigh())+"円");
                text_low.setText("Low:"+Float.toString(ticker.getLow())+"円");
                text_volume.setText("Volume:"+Float.toString(ticker.getVolume())+"BTC");
                text_bid.setText("Bid:"+Float.toString(ticker.getBid())+"円");
                text_ask.setText("Ask:"+Float.toString(ticker.getAsk())+"円");
 
            }

            @Override
            public void onFailure(Call<Data> call, Throwable t) {
            }
        });
Call<Data> btc = service.API("btc_jpy");

の()内でcurrency_pairを指定することができる。
あと、enqueueを使うと非同期処理になり、executeを使うと同期処理になる(エラーが特定バージョン以降でちゃうけど)。

#実行結果
Screenshot_1512984764.png

27
27
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
27
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?