android使用retrofit

build.gradle

compile group: 'com.squareup.retrofit', name: 'converter-gson', version: '2.0.0-beta2'

config

public class RestAdapter {

    private final String API = "http://192.168.0.102:8080/";
    private Retrofit retrofit;

    public RestAdapter() {
        // Creates the json object which will manage the information received
        GsonBuilder builder = new GsonBuilder();

        // Register an adapter to manage the date types as long values
//        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
//            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
//                return new Date(json.getAsJsonPrimitive().getAsLong());
//            }
//        });
//
//        builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        builder.registerTypeAdapter(Date.class, new GsonUTCDateAdapter());

        Gson gson = builder.create();
        this.retrofit = new Retrofit.Builder()
                .baseUrl(API)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }
}

api

public interface ApiService {

    @GET("article/list")
    Call<List<Article>> getByDate(@Query("begin")String begin, @Query("end")String end);

    @GET("article/tags")
    Call<List<String>> getTags();

    @POST("article/{id}")
    Call<Known> update(@Path("id") String id,@Body Article article);

    @POST("article")
    Call<Void> create(@Body Article article);

    @DELETE("article/{id}")
    Call<Void> delete(@Path("id") String id);

}

创建接口实例

ApiService apiService = new RestAdapter().getRetrofit().create(ApiService.class);

之后正常调用即可。同步的话,直接execute,比如

Call<List<Article>> call = apiService.getByDate(begin,end);
        Response<List<Article>> resp = null;
        try {
            resp = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }

docs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值