封装okHttp 上下刷新

本文介绍了一个使用OkHttp进行GET和POST请求的封装类HttpUtils,该类支持传递参数、处理响应并回调结果。同时展示了如何在MainActivity中调用此工具类获取数据,并通过RecyclerView展示结果。

//封装Ok
package com.example.x;
import android.os.Handler;
import java.io.IOException;
import java.util.Map;
import android.os.Handler;
import android.util.Log;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 壹颗大金星 on 2017/11/9.
 */

public class HttpUtils {
    private static volatile HttpUtils instance;
    private static Handler handler = new Handler();

    private HttpUtils(){

    }
    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }
    //get请求
    public void get(String url, Map<String,String> map, final CallBack callBack, final Class c){
        //对url和参数做拼接处理
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(url);
        //判断是否存在?   if中是存在
        if(stringBuffer.indexOf("?")!=-1 ){
            //判断?是否在最后一位    if中是不在最后一位
            if(stringBuffer.indexOf("?")!=stringBuffer.length()-1){
                stringBuffer.append("&");
            }
        }else{
            stringBuffer.append("?");
        }
        for(Map.Entry<String,String> entry:map.entrySet()){
            stringBuffer.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        //判断是否存在&   if中是存在
        if(stringBuffer.indexOf("&")!=-1){
            stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
        }


        //1:创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor())
                .build();
        //2:创建Request对象
        final Request request = new Request.Builder()
                .get()
                .url(stringBuffer.toString())
                .build();
        //3:创建Call对象
        Call call = okHttpClient.newCall(request);
        //4:请求网络
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                //拿到数据解析
                final Object o = new Gson().fromJson(result, c);
                //当前是在子线程,回到主线程中
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //回调
                        callBack.onSuccess(o);
                    }
                });
            }
        });

    }
    //post请求
    public void post(String url, Map<String,String> map, final CallBack callBack, final Class c){
        //1:创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2:提供post请求需要的body对象
        FormBody.Builder builder = new FormBody.Builder();
        for(Map.Entry<String,String> entry:map.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody body = builder.build();
        //3:创建Request对象
        final Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        //4:创建Call对象
        Call call = okHttpClient.newCall(request);
        //5:请求网络
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                //拿到数据解析
                final Object o = new Gson().fromJson(result, c);
                //当前是在子线程,回到主线程中
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //回调
                        callBack.onSuccess(o);
                    }
                });
            }
        });
    }
}


//MainActivity
package com.example.x;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
imort java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private XRecyclerView xrv;
    private int i;
    private XRaDAPTER adapter;
    private List<Bean.SongListBean> list;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        xrv =(XRecyclerView)findViewById(R.id.xrv);
        //设置上拉
        xrv.setPullRefreshEnabled(true);
        xrv.setLoadingMoreEnabled(true);
        xrv.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrv.setLaodingMoreProgressStyle(ProgressStyle.BallClipRotate);

//        loaddata(0);


        //设置监听
        xrv.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        i=0;
                        list.clear();
                        loaddata(i);
                        adapter.notifyDataSetChanged();
                        xrv.refreshComplete();
                    }
                },3000);

            }

            @Override
            public void onLoadMore() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        i++;
                        loaddata(i);
                        list.addAll(list);
                        xrv.loadMoreComplete();
                    }
                },3000);

            }
        });
        //创建数据集合
        loaddata(i);
    }
    private void loaddata(int i){
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance().get("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=" + i, map, new CallBack() {

            @Override
            public void onSuccess(Object o) {
                Bean bean=(Bean) o;
                list = bean.getSong_list();
                //添加适配器
                adapter = new XRaDAPTER(MainActivity.this, list);
                xrv.setAdapter(adapter);
                LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false);
                xrv.setLayoutManager(manager);

            }
            @Override
            public void onFailed(Exception e) {

            }
        },Bean.class);
    }
}





//recyclerview 适配器
package com.example.x;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;

/**
 * Created by on 2017/11/12.
 */

public class XRaDAPTER extends RecyclerView.Adapter<XRaDAPTER.ViewHolder> {

    private Context context;
    private List<Bean.SongListBean>  list;

    public XRaDAPTER(Context context, List<Bean.SongListBean> list) {
        this.context = context;
        this.list = list;
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        private final ImageView img;
        private final TextView tv;

        public ViewHolder(View itemView) {
            super(itemView);
            img =(ImageView)itemView.findViewById(R.id.img);
            tv=(TextView)itemView.findViewById(R.id.tv);
        }
    }
    @Override
    public XRaDAPTER.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflate = View.inflate(context, R.layout.item, null);
        ViewHolder holder = new ViewHolder(inflate);
        return holder;
    }

    @Override
    public void onBindViewHolder(XRaDAPTER.ViewHolder holder, int position) {
        Glide.with(context).load(list.get(position).getPic_big()).into(holder.img);
        holder.tv.setText(list.get(position).getTitle());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}
public interface CallBack {
    void onSuccess(Object o);
    void onFailed(Exception e);
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值