基本数据请求

通过okhttp3这个网络库请求数据

看到okhttp3这个名字估计同学们都想到它是干什么的了,它是一个http数据请求库,封装得很好,也很好用,下面用我做的一个小请求方法来跟大家介绍一下它是如何使用的。

关联远程库:compile ‘com.squareup.okhttp3:okhttp:3.3.1’

我们还是先看代码吧

public class BaseRequest {
    public static final MediaType mMEDIA_TYPE = MediaType.parse("application/json;charset=utf-8");
    static final
    @Nullable
    File baseDir = UIUtils.getContext().getCacheDir();
    static OkHttpClient mHttpUtils;
    //创建一个线程池
    static Executor executor = Executors.newCachedThreadPool();

    //获得网络工具的对象
    private static OkHttpClient getHttpUtils() {

        if (null == mHttpUtils) {
            mHttpUtils = new OkHttpClient().newBuilder().cache(new Cache(baseDir, 1024 * 1024 *
                    10)).build();
        }
        return mHttpUtils;
    }

    //获得网络连接的线程池
    private static Executor getExecutor() {
        if (null == executor) {
            executor = Executors.newCachedThreadPool();
        }
        return executor;
    }

    //方法
    public enum HttpRequestMethod {
        GET, POST, PUT, DELETE
    }


    //基本的封装,请求一般的数据结构
    /**
     *
     * @param context  上下文
     * @param mMethod  枚举的几个请求方法,选其一就行了
     * @param url      请求的url
     * @param requestJson   请求的参数,我们可以先转化为haspmap再转化为字符串,下面会有帮助类
     * @param headerMap     http的请求头,以haspmap的形式
     * @param mHttpResponse 请求回调
     */
    private static void baseRequest(final Context context, final HttpRequestMethod mMethod, final
    String url, final String requestJson, final Map<String, String> headerMap, final HttpResponse mHttpResponse) {
        getExecutor().execute(new Runnable() {

            private String mResponseString;

            @Override
            public void run() {
                RequestBody body = null;
                if (requestJson != null) {
                    body = create(mMEDIA_TYPE, requestJson);
                }

                Request.Builder builder = new Request.Builder().url(url);
                if (null != headerMap) {
                    for (String key : headerMap.keySet()) {
                        if (headerMap.get(key) != null) {
                            builder.addHeader(key, headerMap.get(key));
                        }
                    }
                }

                if (mMethod == HttpRequestMethod.PUT) {
                    builder.put(body);
                }
                if (mMethod == HttpRequestMethod.POST) {
                    builder.post(body);
                }
                if (mMethod == HttpRequestMethod.GET) {
                    builder.get();
                }
                if (mMethod == HttpRequestMethod.DELETE) {
                    builder.delete(body);
                }
                Response response = null;
                try {
                    response = getHttpUtils().newCall(builder.build()).execute();//这行的作用是保存缓存回来的请求
                    mResponseString = response.body().string();
                    mHttpResponse.success(response.code(), mResponseString);


                } catch (IOException e) {
                    e.printStackTrace();
                    mHttpResponse.fail(0, e, "网络请求失败");
                }
            }
        });
    }



    //下面这个方法主要是针对头像图片的上传的方法,必须使用的是post方法,大家有兴趣的话可以了解
    public static final MediaType mMEDIA_UPLOAD_TYPE = MediaType.parse("image/png");

    /**
     * form-data upload
     * @param mMethod   同样是请求方法
     * @param url       请求url
     * @param fileKey
     * @param file      储存图片的文件
     * @param headerMap 请求头
     * @param mHttpResponse  请求回调
     */
    public static void uploadByteRequest(final HttpRequestMethod mMethod, final String url, final
    String fileKey, final File file, final Map<String, String> headerMap, final HttpResponse
                                                 mHttpResponse) {
        getExecutor().execute(new Runnable() {
            @Override
            public void run() {


                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart(fileKey, file.getName(), RequestBody.create
                                (mMEDIA_UPLOAD_TYPE, file)).build();

                Request.Builder builder = new Request.Builder().url(url);
                if (null != headerMap) {
                    for (String key : headerMap.keySet()) {
                        builder.addHeader(key, headerMap.get(key));
                    }
                }
                if (mMethod == HttpRequestMethod.PUT) {
                    builder.put(body);
                }
                if (mMethod == HttpRequestMethod.POST) {
                    builder.post(body);
                }
                if (mMethod == HttpRequestMethod.GET) {
                    builder.get();
                }
                if (mMethod == HttpRequestMethod.DELETE) {
                    builder.delete(body);
                }
                Response response = null;
                try {
                    response = getHttpUtils().newCall(builder.build()).execute();
                    mHttpResponse.success(response.code(), response.body().string());

                } catch (IOException e) {
                    e.printStackTrace();
                    mHttpResponse.fail(0, e, "网络请求失败");
                }
            }
        });
    }

    public interface HttpResponse {
        void success(int code, String responseString);

        void fail(int code, Exception e, String responseString);
    }


    //这个函数是直接把response作为参数返回,至于为什么要这么做,主要是获取一些文件流的形式,例如版本更新的时候需要下载apk文件,这时就要这个方法了
    public static void requestForResponse(final HttpRequestMethod mMethod, final String url,
                                          final String
                                                  requestJson, final Map<String, String>
                                                  headerMap, final HttpResponseItself
                                                  httpResponseItself) {
        getExecutor().execute(new Runnable() {
            @Override
            public void run() {
                RequestBody body = null;
                if (requestJson != null) {
                    body = create(mMEDIA_TYPE, requestJson);
                }

                Request.Builder builder = new Request.Builder().url(url);
                if (null != headerMap) {
                    for (String key : headerMap.keySet()) {
                        builder.addHeader(key, headerMap.get(key));
                    }
                }
                if (mMethod == HttpRequestMethod.PUT) {
                    builder.put(body);
                }
                if (mMethod == HttpRequestMethod.POST) {
                    builder.post(body);
                }
                if (mMethod == HttpRequestMethod.GET) {
                    builder.get();
                }
                if (mMethod == HttpRequestMethod.DELETE) {
                    builder.delete(body);
                }
                Response response = null;
                try {
                    response = getHttpUtils().newCall(builder.build()).execute();
                    httpResponseItself.success(response.code(), response);

                } catch (IOException e) {
                    e.printStackTrace();
                    httpResponseItself.fail(0, e, "网络请求失败");
                }
            }
        });

    }

    public interface HttpResponseItself {
        void success(int code, Response response);

        void fail(int code, Exception e, String responseString);
    }

    public static String convertRequest(Map<String, String> valuseMap) {

        String jsonString;
        try {
            JSONObject json = new JSONObject();

            for (String key : valuseMap.keySet()) {
                json.put(key, (String) valuseMap.get(key));
            }

            jsonString = json.toString().trim();
        } catch (JSONException e) {
            e.printStackTrace();
            jsonString = "";
        }
        return jsonString;
    }
}

用例:
/**
* 上传头像
*
* @param mContext
* @param imageUrl
* @param mHttpResponse
*/
public static void uploadUserinfoImage(Context mContext, String url, String imageUrl,
BaseRequest.HttpResponse mHttpResponse) {

    BaseRequest.uploadByteRequest(BaseRequest.HttpRequestMethod.POST, url, "avatar", new File
            (imageUrl), UIUtils.getHeaderMap(), mHttpResponse);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值