Android Retrofit的使用

一、添加依赖

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'  
compile 'com.squareup.retrofit2:converter-gson:2.3.0'   // 后面需要用到 

    添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

二、创建数据的实体类

三、创建描述网络请求的借口----采用“注解”描述

public interface GetRequestInterface {
    @FormUrlEncoded
    @POST("rest/v1.0/openapi/bar/{last}")
    Call<BaseEntity<MyInfo>> postCall(@Path("last") String last, @FieldMap Map<String, String> map);
}

注:上述第一个参数last是接口的最后一部分,后面的map是把所有参数装进一个map集合里传过来

public class MainModelImp implements MainModel {
    @Override
    public void getDataFromNet(Map map, final OnDataListener listener) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.yjcul.com:8081/BAR/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GetRequestInterface request = retrofit.create(GetRequestInterface.class);
        Call call = request.postCall("getDeviceState", map);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.e("tag", "++++>" + response.body());
                listener.getData(response.body());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                listener.getData("ERROR");
            }
        });
    }

    @Override
    public void stopRequest() {
        Log.e("tag", "停止网路请求");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值