OkHttp的封装

okhttp的封装本人自己封装的如有更好的请指正

1、post的方法。

<span style="font-size:18px;">public class OkhttpUtils {
    private static final String TAG = "OkhttpUtils";

    private static  Gson gson = new Gson();//创建gson对象
    private static String string;
    private static OkHttpClient client =new OkHttpClient();//okhttp对象

    public interface  EntiyData{//创建接口
        void  getEntiy(Object o);
    }
    private static  EntiyData data;
    public  static void  setGetEntiydata(EntiyData data1){
        data=data1;
    }
    //网络post请求
//Type是所有类的类型包括Javabeen
    public static  void post(Map<String,String>map, String path, final Context context, final Type cla){

    FormBody.Builder builder = new FormBody.Builder();
    Set<Map.Entry<String,String>>entries = map.entrySet();//用entryset的方法遍历map集合
    for (Map.Entry<String ,String>entry:entries){
        builder.add(entry.getKey(),entry.getValue());
    }
    FormBody body = builder.build();
    Request request = new Request.Builder()
            .url(path)
            .post(body)
            .build();
    Call call = client.newCall(request);
        //用这种方法不用创建子线程
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Toast.makeText(context,"下载数据失败",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()){
                string=response.body().string();
                Log.i(TAG,"获取的数据:"+string);

                Object o = gson.fromJson(string, cla);
                //回调结果
                data.getEntiy(o);


            }
            else{
                Log.e(TAG, "失败" );
        }

        }
    });
</span>
2、get方法。

<span style="font-size:18px;">  //网络get请求
    public  static void  get(final Context context, String url, final Type clas){
        final Request request1 = new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call1 = client.newCall(request1);
        call1.enqueue(new Callback() {



            @Override
            public void onFailure(Call call, IOException e) {
                    Toast.makeText(context,"获取数据失败",Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    String string1 = response.body().string();
                    Object o1 = gson.fromJson(string1, clas);
                    data.getEntiy(o1);
                }

            }
        });


    }</span>



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值