一个简单明了的OKhttp封装类

来源:互联网 发布:mac book pro 201515.4 编辑:程序博客网 时间:2024/05/29 09:34

本篇博客Demo:http://download.csdn.net/download/g_ying_jie/10134576

单例化工具类,获取主线程handle回调结果

public class OkHttpUtil {    private Handler handler;    private OkHttpClient client;    private OkHttpUtil() {        client = new OkHttpClient();        client.setConnectTimeout(30, TimeUnit.SECONDS);        handler = new Handler(Looper.getMainLooper());    }    private static class SingleHolder {        public static final OkHttpUtil instance = new OkHttpUtil();    }    public static OkHttpUtil getInstance() {        return SingleHolder.instance;    }}

Get请求、没有请求参数形式

/**     * 异步线程访问网络     * get请求     */    public void get(String url, final HttpCallBack httpCallBack) {        Request request = new Request.Builder()                .url(url)                .build();        enqueue(request, httpCallBack);    }


Get请求,带参数请求

/**     * 异步线程访问网络     * get请求 带Body请求体     */    public void get(String url, HashMap maps, final HttpCallBack httpCallBack) {        StringBuffer urlBuffer = new StringBuffer(url);        Iterator iterator = maps.entrySet().iterator();        while (iterator.hasNext()) {            Map.Entry entry = (Map.Entry) iterator.next();            urlBuffer.append((String) entry.getKey()).append("=").append((String) entry.getValue()).append("&");        }        urlBuffer.deleteCharAt(urlBuffer.length() - 1);        Request request = new Request.Builder()                .url(urlBuffer.toString())                .build();        enqueue(request, httpCallBack);    }

Post请求 键值对数据体

/**     * 异步线程访问网络     * post请求 键值对数据体     */    public void post(String url, HashMap maps, final HttpCallBack httpCallBack) {        FormEncodingBuilder formBuilder = new FormEncodingBuilder();        Iterator iterator = maps.entrySet().iterator();        while (iterator.hasNext()) {            Map.Entry entry = (Map.Entry) iterator.next();            formBuilder.add((String) entry.getKey(), (String) entry.getValue());        }        Request request = new Request.Builder()                .url(url)                .post(formBuilder.build())                .build();        enqueue(request, httpCallBack);    }

Post请求 Json数据体

/**     * 异步线程访问网络     * post请求 Json数据体     */    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");    public void post(String url, String json, final HttpCallBack httpCallBack) {        RequestBody body = RequestBody.create(JSON, json);        Request request = new Request.Builder()                .url(url)                .post(body)                .build();        enqueue(request, httpCallBack);    }

Post方式上传文件

     /**     * Post方式提交文件     */    private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");    public void postFile(File file, String path, final HttpCallBack httpCallBack) {        final Request request = new Request.Builder()                .url(path)                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))                .build();        enqueue(request, httpCallBack);    }

@文件下载

/**     * 异步下载文件     * @param url     * @param destFileDir 本地文件存储的文件夹     */    private void downloadFile(final String url, final String destFileDir, final HttpCallBack httpCallBack) {        final Request request = new Request.Builder()                .url(url)                .build();        client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(final Request request, final IOException e) {                handler.post(new Runnable() {                    @Override                    public void run() {                        httpCallBack.onFailure(request, e);                    }                });            }            @Override            public void onResponse(Response response) {                InputStream is = null;                FileOutputStream fos = null;                byte[] buf = new byte[2048];                int len = 0;                try {                    is = response.body().byteStream();                    final File file = new File(destFileDir, getFileName(url));                    fos = new FileOutputStream(file);                    while ((len = is.read(buf)) != -1) {                        fos.write(buf, 0, len);                    }                    fos.flush();                    //如果下载文件成功,参数为文件的绝对路径                    handler.post(new Runnable() {                        @Override                        public void run() {                            httpCallBack.onResponse(file.getAbsolutePath());                        }                    });                } catch (final IOException e) {                    handler.post(new Runnable() {                        @Override                        public void run() {                            httpCallBack.onFailure(request, e);                        }                    });                } finally {                    try {                        if (is != null) is.close();                    } catch (IOException e) {                    }                    try {                        if (fos != null) fos.close();                    } catch (IOException e) {                    }                }            }        });    }    private String getFileName(String path) {        int separatorIndex = path.lastIndexOf("/");        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());    }

@一些调用的方法和接口(不带Callback的执行即为同步执行)

    private void enqueue(Request re, final HttpCallBack httpCallBack) {        client.newCall(re).enqueue(new Callback() {            @Override            public void onFailure(final Request request, final IOException e) {                handler.post(new Runnable() {                    @Override                    public void run() {                        httpCallBack.onFailure(request, e);                    }                });            }            @Override            public void onResponse(Response response) throws IOException {                final String result = response.body().string();                handler.post(new Runnable() {                    @Override                    public void run() {                        httpCallBack.onResponse(result);                    }                });            }        });    }    public interface HttpCallBack {        void onFailure(Request request, IOException e);        void onResponse(String response);    }

@Activity中的应用

package com.gu.okhttp;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import com.gu.okhttp.bean.BaseAppEntity;import com.gu.okhttp.bean.DataBeanEntity;import com.gu.okhttp.utils.OkHttpUtil;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;import java.io.IOException;import java.lang.reflect.Type;public class MainActivity extends AppCompatActivity {    public static final String POST_URL = "http://api/CodeBook/Adviser/Login";    public static final String Json = "{\"loginname\":\"hahaha\",\"password\":\"123456\"}";    public static final String GET_URL = "http://api/CodeBook/Book/GetMyBookList?adviser_id=10&name=&order_field=reader_count&sort=1&pageIndex=1&pageSize=10";    //装载数据    private BaseAppEntity<DataBeanEntity> entity;    private Gson gson;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        gson = new Gson();    }    public void onPost(View view) {        OkHttpUtil.getInstance().post(POST_URL, Json, new OkHttpUtil.HttpCallBack() {            @Override            public void onFailure(Request request, IOException e) {            }            @Override            public void onResponse(String response) {            }        });    }    public void onGet(View view) {        OkHttpUtil.getInstance().get(GET_URL, new OkHttpUtil.HttpCallBack() {            @Override            public void onFailure(Request request, IOException e) {            }            @Override            public void onResponse(String response) {                Type type = new TypeToken<BaseAppEntity<DataBeanEntity>>() {                }.getType();                entity = gson.fromJson(response, type);            }        });    }}


这里还可以视项目需求封装一个Javabean的基类,以泛型传入具体的实现类,直接返回数据对象。具体使用可以参考demo。