Retrofit 学习

https://github.com/square/retrofit
http://square.github.io/retrofit/

优酷视频地址:
视频1
视频2
视频3
视频4

示例1:

package com.example.paydemo.retrofit;

import org.junit.Test;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;

/**
 * Created by Administrator on 2016/6/8.
 */
public class RetroFitTest {
    public interface Service {
        @GET("/")  //网址下的子目录  /根目录
        Call getBaidu();
    }

    @Test
    public void test1() {
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("http://www.baidu.com")
                .addConverterFactory(new Converter.Factory() {
                    @Override
                    public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
                        return new Converter() {
                            @Override
                            public String convert(ResponseBody value) throws IOException {
//                                return value.string();
                                return "aaa";
                            }
                        };
                    }
                })
                .build();
        Service service = retrofit1.create(Service.class);
        Call baidu = service.getBaidu();
        baidu.enqueue(new Callback() {  //异步请求
            @Override
            public void onResponse(Call call, Response response) {
                String body = response.body(); //是自定义的Converter中返回的值
                System.out.println(body);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                System.out.println("onFailure");
            }
        });
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


package com.example.paydemo.retrofit;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import org.junit.Test;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

/**
 * Created by Administrator on 2016/6/8.
 */
public class RetroFitTest2 {

    //    http://www.tngou.net/api/cook/list
    public static class Bean {
        private boolean status;
        private int total;
        private List tngou;

        public boolean isStatus() {
            return status;
        }

        public void setStatus(boolean status) {
            this.status = status;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }

        public List getTngou() {
            return tngou;
        }

        public void setTngou(List tngou) {
            this.tngou = tngou;
        }

        public static class TngouEntity {
            private int count;
            private String description;
            private int fcount;
            private String food;
            private int id;
            private String images;
            private String img;
            private String keywords;
            private String name;
            private int rcount;

            public int getCount() {
                return count;
            }

            public void setCount(int count) {
                this.count = count;
            }

            public String getDescription() {
                return description;
            }

            public void setDescription(String description) {
                this.description = description;
            }

            public int getFcount() {
                return fcount;
            }

            public void setFcount(int fcount) {
                this.fcount = fcount;
            }

            public String getFood() {
                return food;
            }

            public void setFood(String food) {
                this.food = food;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getImages() {
                return images;
            }

            public void setImages(String images) {
                this.images = images;
            }

            public String getImg() {
                return img;
            }

            public void setImg(String img) {
                this.img = img;
            }

            public String getKeywords() {
                return keywords;
            }

            public void setKeywords(String keywords) {
                this.keywords = keywords;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public int getRcount() {
                return rcount;
            }

            public void setRcount(int rcount) {
                this.rcount = rcount;
            }
        }

    }

    public static class Bean2 {

        @SerializedName("status")
        private boolean status;
        @SerializedName("total")
        private int total;
        @SerializedName("tngou")
        private List tngou;

        @Override
        public String toString() {
            return "Bean2{" +
                    "status=" + status +
                    ", total=" + total +
                    ", tngou=" + tngou +
                    '}';
        }

        public boolean isStatus() {
            return status;
        }

        public void setStatus(boolean status) {
            this.status = status;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }

        public List getTngou() {
            return tngou;
        }

        public void setTngou(List tngou) {
            this.tngou = tngou;
        }

        public static class TngouEntity {
            @SerializedName("count")
            private int count;
            @SerializedName("description")
            private String description;
            @SerializedName("fcount")
            private int fcount;
            @SerializedName("food")
            private String food;
            @SerializedName("id")
            private int id;
            @SerializedName("images")
            private String images;
            @SerializedName("img")
            private String img;
            @SerializedName("keywords")
            private String keywords;
            @SerializedName("name")
            private String name;
            @SerializedName("rcount")
            private int rcount;

            @Override
            public String toString() {
                return "TngouEntity{" +
                        "count=" + count +
                        ", description='" + description + '\'' +
                        ", fcount=" + fcount +
                        ", food='" + food + '\'' +
                        ", id=" + id +
                        ", images='" + images + '\'' +
                        ", img='" + img + '\'' +
                        ", keywords='" + keywords + '\'' +
                        ", name='" + name + '\'' +
                        ", rcount=" + rcount +
                        '}';
            }

            public int getCount() {
                return count;
            }

            public void setCount(int count) {
                this.count = count;
            }

            public String getDescription() {
                return description;
            }

            public void setDescription(String description) {
                this.description = description;
            }

            public int getFcount() {
                return fcount;
            }

            public void setFcount(int fcount) {
                this.fcount = fcount;
            }

            public String getFood() {
                return food;
            }

            public void setFood(String food) {
                this.food = food;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getImages() {
                return images;
            }

            public void setImages(String images) {
                this.images = images;
            }

            public String getImg() {
                return img;
            }

            public void setImg(String img) {
                this.img = img;
            }

            public String getKeywords() {
                return keywords;
            }

            public void setKeywords(String keywords) {
                this.keywords = keywords;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public int getRcount() {
                return rcount;
            }

            public void setRcount(int rcount) {
                this.rcount = rcount;
            }
        }
    }

    public interface Service {
        /**
         * get方式获取数据
         *
         * @param cate
         * @param id
         * @param page
         * @param rows
         * @return
         */
        @GET("/api/{cate}/list")
        Call getList(@Path("cate") String cate, @Query("id") int id,
                            @Query("page") int page, @Query("rows") int rows);

        /**
         * 以form形式提交数据
         *
         * @param cate
         * @param id
         * @param page
         * @param rows
         * @return
         */
        @POST("/api/{cate}/list")
        @FormUrlEncoded
        Call postList(@Path("cate") String cate, @Field("id") int id,
                             @Field("page") int page, @Field("rows") int rows);


    }

    @Test
    public void test1() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.tngou.net")
//                .addConverterFactory(new Converter.Factory() {
//                    @Override
//                    public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
//                        return new Converter() {
//
//                            @Override
//                            public String convert(ResponseBody value) throws IOException {
//                                return value.string();
//                            }
//                        };
//                    }
//                })
//        compile 'com.squareup.retrofit2:converter-simplexml:2.0.2' 解析xmL
//
                // 引入 compile 'com.squareup.retrofit2:converter-gson:2.0.2'
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Service service = retrofit.create(Service.class);
//        Call beans = service.getList("cook",0,1,5);
//        try {
//            Response res = beans.execute();
//            Bean2 body = res.body();
//            System.out.println(body.getTngou().size());
//            System.out.println(body);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Call beans = service.postList("cook", 0, 1, 5);
        try {
            Response res = beans.execute();
            Bean2 body = res.body();
            System.out.println(body.getTngou().size());
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

也可以直接提交okhttp的requestbody

public interface Service {
      @Headers("Content-Type:application/json")
      @POST("/artbean/api/api1/Home/Life/LifeNewsID")
      Call postBody(@Body RequestBody body);

      @Headers("Content-Type:application/json")
      @POST("/artbean/api/api1/Home/Address/editAddress")
      Call editAddress(@Body RequestBody body);

      @GET("/artbean/api/api1/home/conlist/index")
      Call getApiList();
  }

可参见官方的文档

你可能感兴趣的:(Retrofit 学习)