当先锋百科网

首页 1 2 3 4 5 6 7

1,此篇文章主要阐述怎么用okhttp逻辑简洁的请求到服务器JSON数据信息;
2,下面分析的思路主要这几点:

  • 新建bean类文件,里面放置gson解析的完整json数据;
  • 建立接口文件;
  • 建立参数和日志拦截器的文件信息;

bean.Demo.java

package com.rx.rxnet.bean;

import java.util.List;

/**
 * Created by rnd on 2018/4/27.
 */

public class Demo {

    /**
     * code : 200
     * tips : ok
     * message : success
     * devices : [{"deviceid":1,"userid":3,"username":"demo","devicename":"TPYBoard v202","deviceaddre":"5C:CF:7F:0D:85:65","addtime":1520861232353},{"deviceid":2,"userid":3,"username":"demo","devicename":"Computer012","deviceaddre":"a5:a9:a9:ac:a0:a6","addtime":1516528220580}]
     */

    private String code;
    private String tips;
    private String message;
    private List<DevicesBean> devices;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getTips() {
        return tips;
    }

    public void setTips(String tips) {
        this.tips = tips;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<DevicesBean> getDevices() {
        return devices;
    }

    public void setDevices(List<DevicesBean> devices) {
        this.devices = devices;
    }

    public static class DevicesBean {
        /**
         * deviceid : 1
         * userid : 3
         * username : demo
         * devicename : TPYBoard v202
         * deviceaddre : 5C:CF:7F:0D:85:65
         * addtime : 1520861232353
         */

        private int deviceid;
        private int userid;
        private String username;
        private String devicename;
        private String deviceaddre;
        private long addtime;

        public int getDeviceid() {
            return deviceid;
        }

        public void setDeviceid(int deviceid) {
            this.deviceid = deviceid;
        }

        public int getUserid() {
            return userid;
        }

        public void setUserid(int userid) {
            this.userid = userid;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getDevicename() {
            return devicename;
        }

        public void setDevicename(String devicename) {
            this.devicename = devicename;
        }

        public String getDeviceaddre() {
            return deviceaddre;
        }

        public void setDeviceaddre(String deviceaddre) {
            this.deviceaddre = deviceaddre;
        }

        public long getAddtime() {
            return addtime;
        }

        public void setAddtime(long addtime) {
            this.addtime = addtime;
        }
    }
}

BaseConstant.java

public class BaseConstant {
    public static final String SERVER_ADDRESS= "https://wfuwuqi.com";
}

NetApi.java

package com.rx.rxnet.net;


import com.rx.rxnet.bean.Demo;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public interface NetApi {
    @POST("getData")
    Call<Demo> getData(@QueryMap Map<String,Object> params);
}

RetrofitFactory.java

package com.rx.rxnet.net;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitFactory {

    private Retrofit retrofit;

    //通用拦截器
    private Interceptor interceptor;


    //单列模式
    private static class SingletonHolder{
        private static final RetrofitFactory INSTANCE = new RetrofitFactory();
    }


    public RetrofitFactory(){
        interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        //返回参数
                        .addHeader("Content_Type","application/json")
                        //添加编码格式
                        .addHeader("charset","UTF-8")
                        //token 可以将存为传入到服务器的token
                        .addHeader("token", "1")
                        .build();
                return chain.proceed(request);
            }
        };


        //Retrofit实例化
        retrofit =new Retrofit.Builder()
                .baseUrl(BaseConstant.SERVER_ADDRESS)
                //与Gson结合
                .addConverterFactory(GsonConverterFactory.create())
                //OKHttpClient初始化
                .client(initClient())
                .build();
    }

    /**
     OKHttp创建
     */
    private OkHttpClient initClient(){
        return new OkHttpClient.Builder()
                //日志拦截器
                .addInterceptor(initLogInterceptor())
                //处理头部拦截器
                .addInterceptor(interceptor)
                //连接时间 10秒
                .connectTimeout(, TimeUnit.SECONDS)
                //超时时间 10秒
                .readTimeout(, TimeUnit.SECONDS)
                .build();
    }

    /**
     日志拦截器
     */
    private HttpLoggingInterceptor initLogInterceptor(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //日志级别 Body级别
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return interceptor;
    }


    /**
     * 获取RetrofitServiceManager
     * @return
     */
    public static RetrofitFactory getInstance(){
        return RetrofitFactory.SingletonHolder.INSTANCE;
    }


    /**
     * 获取对应的Service
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T  create(Class<T> service){
        return retrofit.create(service);
    }

}

最后一个主界面MainActivity

public class MainActivity extends AppCompatActivity {

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

    private void getData(){
        Map<String,Object> params = new HashMap<>();
        params.put("action","getAllDevice");
        params.put("username","demo");
        params.put("userid",);

        RetrofitFactory.getInstance().create(NetApi.class).getData(params).enqueue(new Callback<Demo>() {
            @Override
            public void onResponse(Call<Demo> call, Response<Demo> response) {

                for(Demo.DevicesBean dv:response.body().getDevices()){
                    //获取想要的数据
                    Log.i("deviceName->",dv.getDevicename());
                    Log.i("deviceAddre->",dv.getDeviceaddre());
                }
            }
            @Override
            public void onFailure(Call<Demo> call, Throwable t) {
                Log.i("Error",t.getMessage());
            }
        });

    }
}

ok,就这么大功告成了!数据已经全部获取到,大家可以再仔细的看下,若有不懂的可以下方评论或者留言,谢谢!