OKhttp3工具类

本人开发过程中使用到的工具类,记录在此,包含的方法都是自己用到的,并不全面
如有使用者自取
有好的意见或不完善之处欢迎指出

AndroidManifest.xml 里 application中

权限申请

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

android:networkSecurityConfig="@xml/network_security_config"

network-security-config.xml

<network-security-config>
<base-config cleartextTrafficPermitted="true"  />
<domain-config cleartextTrafficPermitted="true" >
    <domain includeSubdomains="true">127.0.0.1</domain>
    <domain includeSubdomains="true">192.168.100.192</domain>
    <domain includeSubdomains="true">qingshanboke.com</domain>
</domain-config>
</network-security-config>

OKhttpUtils

public class OKhttpUtils {

    private static OkHttpClient okHttpClient;

    public OKhttpUtils(){
        okHttpClient=new OkHttpClient().newBuilder()
                .callTimeout(8, TimeUnit.SECONDS)
                .connectTimeout(8,TimeUnit.SECONDS)
                .readTimeout(8,TimeUnit.SECONDS)
                .build();
    }

    private static OKhttpUtils instance;

    public static OKhttpUtils getInstance() {
        if (instance==null){
            instance=new OKhttpUtils();
        }
        return instance;
    }


    //get方法
    public static void get(final String url, final OkhttpCallBack okhttpCallBack){
        try {
            final Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {

                    getInstance();
                    Request request = new Request.Builder()
                            .url(url)
                            .method("GET", null)
                            .addHeader("Accept", "application/json")
                            .addHeader("User-Agent", "apifox/1.0.26 (https://www.apifox.cn)")
                            .build();

                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            okhttpCallBack.onFail(e.getMessage()+"失败的");
                            Log.i("asd",e.getMessage());
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            okhttpCallBack.onSuccess(response);
                            Log.i("asd","OKHTTPUtils连接成功");
                        }
                    });
                }
            });
            thread.start();} catch (Exception e) {
            e.printStackTrace();
            Log.i("asd","OKHTTPUtils连接失败");
        }
    }
    //get方法
    public static void get_token( final String token,final String url, final OkhttpCallBack okhttpCallBack){
        try {
            final Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {

                    getInstance();
                    Request request = new Request.Builder()
                            .url(url)
                            .method("GET", null)
                            .addHeader("Authorization", token)
                            .addHeader("User-Agent", "apifox/1.0.26 (https://www.apifox.cn)")
                            .build();

                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            okhttpCallBack.onFail(e.getMessage()+"asdfghjkl");
                            Log.i("asd",e.getMessage());
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            okhttpCallBack.onSuccess(response);
                            Log.i("asd","OKHTTPUtils连接成功");
                        }
                    });
                }
            });
            thread.start();} catch (Exception e) {
            e.printStackTrace();
            Log.i("asd","OKHTTPUtils连接失败");
        }
    }

    // post json数据  token数据
    public static void post_json(final String token,final String url, final String json,  final OkhttpCallBack okhttpCallBack) throws JSONException {

        try {
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    getInstance();
                    try {
                        JSONObject jsonObject=new JSONObject(json);

                        MediaType mediaType = MediaType.parse("application/json");
                        RequestBody body = RequestBody.create(mediaType,jsonObject.toString() );

                  
                        Request request = new Request.Builder()
                                .url(url)
                                .post(body)
                                .addHeader("Accept", "application/json")
                                .addHeader("Authorization", token)
                                .addHeader("User-Agent", "apifox/1.0.26 (https://www.apifox.cn)")
                                .addHeader("Content-Type", "application/json")
                                .build();
                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                okhttpCallBack.onFail(e.getMessage() + "失败的OKHTTP返回数据");
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                okhttpCallBack.onSuccess(response);
                                Log.i("asd","OKHTTPUtils连接成功");
                            }

                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();  } catch (Exception e) {
            e.printStackTrace();
            Log.i("asd","OKHTTPUtils连接失败");
        }
    }


    // post form数据  token数据
    public static void post_form(final String token, final String title, final String content, final int  id, final OkhttpCallBack okhttpCallBack) throws JSONException {

        try {
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    getInstance();
                    try {

                        MediaType mediaType = MediaType.parse("text/form-data");
                        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)

                                .addFormDataPart("banner_id", String.valueOf(id))
                                .addFormDataPart("title", title)
                                .addFormDataPart("content", content)
                                .build();

                        Request request = new Request.Builder()
                                .url("http://47.102.215.61:8888/news/release_news")
                                .post(body)
                                .addHeader("Accept", "application/json")
                                .addHeader("Authorization", token)
                                .addHeader("User-Agent", "apifox/1.0.26 (https://www.apifox.cn)")
                                .addHeader("Content-Type", "application/json")
                                .build();
                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                okhttpCallBack.onFail(e.getMessage() + "失败的OKHTTP返回数据");
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                okhttpCallBack.onSuccess(response);
                                Log.i("asd","OKHTTPUtils连接成功hh");
                            }

                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();  } catch (Exception e) {
            e.printStackTrace();
            Log.i("asd","OKHTTPUtils连接失败");
        }
    }
    //数据返回
    public interface OkhttpCallBack{
        void onSuccess(Response response) throws IOException;
        void onFail(String error);
    }
}
上一篇:参数注解检查方法入参


下一篇:表现层的设计(二)——MVC如何处理复杂的界面元素