OKGO【配置】

首先在Application里的onCreate()里面初始化网络配置

/**
     * 初始化OKgo的环境配置【可选】
     */
    private void initOkHttp() {
        //使用OkGo内置的log拦截器打印log,如果你觉得不好用,也可以自己写个,这个没有限制。
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor("okgo");
        //log打印级别,决定了log显示的详细程度
        interceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别,决定了log在控制台显示的颜色
        interceptor.setColorLevel(Level.INFO);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //全局的读取超时时间 十分钟
        builder.readTimeout(60 * 1000 * 10, TimeUnit.MILLISECONDS);
        //全局的写入超时时间 十分钟
        builder.writeTimeout(60 * 1000 * 10, TimeUnit.MILLISECONDS);
        //全局的连接超时时间 十分钟
        builder.connectTimeout(60 * 1000 * 10, TimeUnit.MILLISECONDS);
        builder.addInterceptor(interceptor);
        OkHttpClient client = builder.build();
        OkGo.getInstance().init(this).setOkHttpClient(client);
        //可以设置同时上传的任务数量,如果不设置,默认就是1个,改方法只在第一次调用时生效,以后无效,必须在首次执行前设置,否者无效 ,范围1-5之间
        OkUpload.getInstance().getThreadPool().setCorePoolSize(4);
        OkDownload.getInstance().setFolder(FileUtils.path);
        OkDownload.getInstance().getThreadPool().setCorePoolSize(4);
    }

例如:

OKGO【配置】_第1张图片

配置网络请求工具类【这是我自己写的】

/**
 * 联网请求工具类
 *
 * @author mzz
 */
public class HttpUtil {

    /*public static  void postString(String url, String string, final AbsCallback callback) {
        OkGo.post(Http_URL.getBaseUrl() + url)
                .upString(string)
                .execute(callback);
    }*/

    /*public static  void postJson(String url, String json, final AbsCallback callback) {
        OkGo.post(Http_URL.getBaseUrl() + url)
                .upJson(json)
                .execute(callback);
    }*/

    public static  void postJson_Headers(String url, String json, Context context, final AbsCallback callback) {
        String Token = (String) SPUtils.get(context, AppUtils.Token, "");
        String Token_Type = (String) SPUtils.get(context, AppUtils.Token_Type, "");
        OkGo.post(Http_URL.getBaseUrl() + url)
                .headers("Authorization", Token_Type + " " + Token)
                .upJson(json)
                .execute(callback);
    }

    /*public static  void postMap(String url, HashMap map, final AbsCallback callback) {
        OkGo.post(Http_URL.getBaseUrl() + url)
                .params(map)
                .execute(callback);
    }*/

    /*public static  void postBody(String url, RequestBody body, final AbsCallback callback) {
        OkGo.post(Http_URL.getBaseUrl() + url)
                .upRequestBody(body)
                .execute(callback);
    }*/

    /*public static  void getMap(String url, HashMap map, final AbsCallback callback) {
        String Token = (String) SPUtils.get(BaseApplication.getContext(), AppUtils.Token, "");
        String Token_Type = (String) SPUtils.get(BaseApplication.getContext(), AppUtils.Token_Type, "");
        OkGo.get(Http_URL.getBaseUrl() + url)
                .params(map)
                .headers("Authorization", Token_Type + " " + Token)
                .execute(callback);
    }*/

    public static  void getString_Headers(String url, Context context, final AbsCallback callback) {
        String Token = (String) SPUtils.get(BaseApplication.getContext(), AppUtils.Token, "");
        String Token_Type = (String) SPUtils.get(context, AppUtils.Token_Type, "");
        OkGo.get(Http_URL.getBaseUrl() + url)
                .headers("Authorization", Token_Type + " " + Token)
                .execute(callback);
    }

    public static  void postFile_Headers(String url, File file, Context context, final AbsCallback callback) {
        String Token = (String) SPUtils.get(context, AppUtils.Token, "");
        String Token_Type = (String) SPUtils.get(context, AppUtils.Token_Type, "");
        ArrayList files = new ArrayList<>();
        files.clear();
        files.add(file);
        OkGo.post(Http_URL.getBaseUrl() + url)
                .headers("Authorization", Token_Type + " " + Token)
                .addFileParams("file", files)
                .execute(callback);
    }

    /**
     * 上传json字符串
     *
     * @param adress_Http 地址
     * @param strJson     json字符串
     * @return
     */
    public static int postJson(String adress_Http, String strJson) {

        String returnLine = "";
        int code = 0;
        try {

            System.out.println("**************调用的接口地址为**************" + adress_Http);
            System.out.println("**************请求发送的数据为**************" + strJson);
            URL my_url = new URL(adress_Http);
            HttpURLConnection conn = (HttpURLConnection) my_url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(30 * 1000);
//            connection.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");

            Map> requestProperties = conn.getRequestProperties();

            DataOutputStream out = new DataOutputStream(conn
                    .getOutputStream());

            byte[] content = strJson.getBytes();

            out.write(content);
            out.flush();
            out.close(); // flush and close

            code = conn.getResponseCode();

            //读
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            //StringBuilder builder = new StringBuilder();

            String line = "";

            System.out.println("Contents of post request start");

            while ((line = reader.readLine()) != null) {
                returnLine += line;

                System.out.println(line);
            }

            System.out.println("Contents of post request ends");

            reader.close();
            conn.disconnect();
            System.out.println("========返回的结果的为========" + returnLine);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }
}

 这是使用:我统一处理返回值了,如果你不需要的话,可以省略这一步

/**
 * Create by Mazhanzhu on 2019/11/28
 */
public class Login {
    public interface Date {
        void success(String body);
    }

    /**
     * post请求,带请求头。内容自动转换为Json形式
     */
    public static void Post_Header_Date(String url, HashMap map, Activity context, Date date) {
        HttpUtil.postJson_Headers(url.trim(), new Gson().toJson(map), context, new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                if (Login.Success(context, response)) {
                    date.success(response.body());
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                ToastUtils.showToast(response.message());
            }
        });
    }

    /**
     * get请求,带请求头
     */
    public static void getString_Headers(String url, Activity context, Date date) {
        HttpUtil.getString_Headers(url.trim(), context, new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                if (Login.Success(context, response)) {
                    date.success(response.body());
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                ToastUtils.showToast(response.message());
            }
        });
    }

    /**
     * 判断返回数据是否正确
     *
     * @param response 传入的参数
     * @return true 有正常返回数据
     */
    public static boolean Success(Activity context, Response response) {
        Log_Ma.e("网络请求", response);
        switch (response.code()) {
            case 200://代表和自己的后台已经成功链接
                try {
                    JSONObject jsonObject = new JSONObject(response.body());
                    String msg = jsonObject.getString("msg");
                    int code = Integer.parseInt(jsonObject.getString("code"));
                    switch (code) {
                        case 200:
                            return true;
                        case 402:
                            //返回首页
                            context.startActivity(new Intent(context, MainActivity.class));
                            context.finish();
                            ToastUtils.showToast(msg);
                            return false;
                        default:
                            ToastUtils.showToast(msg);
                            return false;
                    }
                } catch (Exception e) {
                    ToastUtils.showToast("注意!返回数据错误");
                    return false;
                }
            case 403:
                ToastUtils.showToast("Token验证失败,请重新登录");
                SPUtils.remove(BaseApplication.getContext(), AppUtils.Token);
                SPUtils.remove(BaseApplication.getContext(), AppUtils.Token_Type);
                context.startActivity(new Intent(context, Activity_Login.class));
//                context.finish();
                return false;
            default:
                try {
                    JSONObject jsonObject = new JSONObject(response.body());
                    String msg = jsonObject.getString("msg");
                    ToastUtils.showToast(msg);
                } catch (Exception e) {
                    ToastUtils.showToast("注意!返回数据错误");
                }
                return false;
        }
    }

    public static HashMap getMap() {
        HashMap map = new HashMap<>();
        return map;
    }
}

具体的使用方式

OKGO【配置】_第2张图片

 

 

你可能感兴趣的:(网络通信,技术总结)