Retrofit 2.1用法(一)

27743 ワード

ブログを書くのは覚えやすいためだけです.続けてほしいです.
本文はただ自分の記憶を便利にするために、知りたいのは下のリンクを通して勉強できます.
公式文書http://square.github.io/retrofit/ githubアドレスhttps://github.com/square/retrofit
テストインターフェースhttp://v.juhe.cn/toutiao/index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe データの戻りフォーマットRetrofit2.1用法(一)_第1张图片
GET方式
一般的な要求方式は、データを解析するためのインターフェースを定義します.
public interface HttpService {
    @GET("index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe")
    Call<Result> testHttpGet();


    // GSON - BEAN
    class Result {
        String reason;
        result result;


        class result {
            String stat;
            ArrayList<data> data;


            class data {
                String title;
                String date;
                String author_name;
                String thumbnail_pic_s;
                String thumbnail_pic_s02;
                String url;
                String uniquekey;
                String type;
                String realtype;

            }
        }


    }
}
データの要求
void textGet() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        Call<HttpService.Result> call = service.testHttpGet();
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {

                Log.d("xxx", response.message());
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
Debug情報が見られます.データはすでに解析されました.
@Pathの使い方は、例えば2つのインターフェースアドレスがあります.
String url = http://v.juhe.cn/eg2/
String url = http://v.juhe.cn/eg1/
@Pathでアドレスをつづり合わせることができます.
 @GET("{eg}") Call<Result> testHttpGet(@Path("eg") String toutiao);
要求方式
void textGet() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        Call<HttpService.Result> call = service.testHttpGet("eg1");
        //Call<HttpService.Result> call = service.testHttpGet("eg2");
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {

                Log.d("xxx", response.message());
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
この方式は主にデカップリングのためです.(注:住所のつなぎ合わせはパラメータをつなぎ合わせることができませんので、ここでは使用法を模擬するだけです.この方法は実際のデータインターフェースだけに役に立ちます.)
@Query使い方(GETとPOST方式は全部使えます)テストインターフェースアドレスhttp://v.juhe.cn/toutiao/index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe
Query方法でパラメータを調べることができます.
@GET("index")
Call<Result> testHttpGet_query(@Query("type") String type, @Query("key") String key);
要求方式
void textGet_query() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);

        Call<HttpService.Result> call = service.testHttpGet_query("top","9e05423f7ac6acf6d0dce3425c4ea9fe");
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
               Log.d("xxx", response.message());

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
@QueryMap使い方インターフェースアドレスhttp://v.juhe.cn/toutiao/index?type=top&key=9e05423f7ac6acf6d0dce3425c4ea9fe
@GET("index")
Call<Result> testHttpGet_ueryMap(@QueryMap HashMap<String, String> map);
void textGet_queryMap() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        HashMap<String,String> map=new HashMap<>();
        map.put("type","top");
        map.put("key","9e05423f7ac6acf6d0dce3425c4ea9fe");
        Call<HttpService.Result> call = service.testHttpGet_ueryMap(map);
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {

                Log.d("xxx", response.message());
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
POST方式
@Query使い方はGETの@Queryを参考にします.
@Bodyの使い方(インターフェースはこの方式をサポートしていません.以下のシミュレーションの使い方)POSTにjsonデータをアップロードするために使用されます.例えばインターフェースはこのようなものです.
String url = http://v.juhe.cn/toutiao/
データをアップロードする必要があります.データを取得することができます.
{"type":"xxx","key":"xxx"}
@POST("toutiao")
Call<Result> testHttpPost(@Body Params params);

class Params {
        String type;
        String key;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public Params(String type, String key) {
            this.type = type;
            this.key = key;
        }
    }
Resultクラスは上記で提供されました.
データの要求
void textPost_body() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);

        Call<HttpService.Result> call = service.testHttpPost_body(new HttpService.Params("top","9e05423f7ac6acf6d0dce3425c4ea9fe"));
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                Log.d("xxx", response.body().reason);
            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {

            }
        });

    }
@Fieldの使い方
@FormUrlEncoded @POST("index") Call<Result> testHttpPost_formUrlEncoded(@Field("type") String type, @Field("key") String key);
 void textPost_formUrlEncoded() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
       Call<HttpService.Result> call = service.testHttpPost_formUrlEncoded("top","9e05423f7ac6acf6d0dce3425c4ea9fe");
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                list = response.body().result.getData();
                updateUi();

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
@FieldMap使い方
@FormUrlEncoded @POST("index") Call<Result> testHttpPost_formUrlEncoded_map(@FieldMap HashMap<String, String> map);
void textPost_formUrlEncoded_map() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "top");
        map.put("key", "9e05423f7ac6acf6d0dce3425c4ea9fe");
        Call<HttpService.Result> call = service.testHttpPost_formUrlEncoded_map(map);
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                list = response.body().result.getData();
                updateUi();

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
コーディング
POST方式を使う時、文字化けが発生したら、中国語をエンコードする必要があります.
//            
 String type =  URLEncoder.encode("  ","UTF-8");
@Headers使い方は直接Headersによって符号化フォーマットを設定することができます.
@Headers("Content-type:application/x-www-from-urlencoded;charset=UTF-8")
@FormUrlEncoded
@POST("index")
Call<Result> testHttpPost_formUrlEncoded_map_headers(@FieldMap HashMap<String, String> map);
@Headerの使い方
@FormUrlEncoded @POST("index") Call<Result> testHttpPost_formUrlEncoded_map_header(@Header("Content-Type") String contentType,@FieldMap HashMap<String, String> map);
void textPost_formUrlEncoded_map_header() throws IOException {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn/toutiao/").addConverterFactory(GsonConverterFactory.create()).build();
        HttpService service = retrofit.create(HttpService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "top");
        map.put("key", "9e05423f7ac6acf6d0dce3425c4ea9fe");
        Call<HttpService.Result> call = service.testHttpPost_formUrlEncoded_map_header("Content-type:application/x-www-from-urlencoded;charset=UTF-8",map);
        call.enqueue(new Callback<HttpService.Result>() {
            @Override
            public void onResponse(Call<HttpService.Result> call, Response<HttpService.Result> response) {
                list = response.body().result.getData();
                updateUi();

            }

            @Override
            public void onFailure(Call<HttpService.Result> call, Throwable t) {
                Log.d("xxx", t.getMessage());
            }
        });

    }
デモの効果図
ソースアドレス
https://github.com/jiangzehui/RetrofitDemo