okhttp3的封装

第三方封装:

​
 https://github.com/hongyangAndroid/okhttputils

此处借鉴鸿洋大神分享的框架:https://github.com/hongyangAndroid/okhttputils

还有鸿洋大神的博客:https://blog.csdn.net/lmj623565791/article/details/47911083

使用前导入:

implementation 'com.zhy:okhttputils:2.6.2'

​​​​​​Okhttp3封装_Snow_Ice_Yang的博客-CSDN博客_okhttp3封装

​

自己封装一:

package com.jiuddata.common.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * http通信服务封装
 *
 * @author:debug
 */
public class HttpService {
 
    private static final Logger log = LoggerFactory.getLogger(HttpService.class);
 
    private OkHttpClient client = new OkHttpClient();

/*
使用
  Map<String, String> headerMap=new HashMap<>();
            headerMap.put("Content-Type","application/json");
            Map<String, String> bodyParams=new HashMap<>();
            bodyParams.put("images_path","E:/python_project/images/scottsdale");
            bodyParams.put("out_put","E:/python_project/images/scottsdale/a.jpg");
            bodyParams.put("v5put","E:/python_project/images/scottsdale");
            HttpService httpService = new HttpService();
            String post = httpService.post("http://192.168.0.24:8082/image_fusion", headerMap,
                    "application/json",JSON.toJSONString(bodyParams));
            System.err.println(post);
*/
//    /**
//     * OkHttpClient调用dubboOne的服务提供的http协议
//     */
//    private OkHttpClient httpClient=new OkHttpClient();
//
//    @Autowired
//    private ObjectMapper objectMapper;
//    /**
//     * 去请求dubboOnew的server中的text3接口
//     * @param user
//     */
//    public void pushOrder(User user){
//        try {
//            //构造builder
//            Request.Builder builder=new Request.Builder()
//                    .url("http://127.0.0.1:9013/v1/record/text3")
//                    .header("Content-Type","application/json");
//            //构造请求体
//            RequestBody requestBody= RequestBody.create(MediaType.parse("application/json"),
//                    objectMapper.writeValueAsString(user));
//            //构造请求
//            Request request=builder.post(requestBody).build();
//            //发起请求
//            Response response=httpClient.newCall(request).execute();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
    /**
     * 构造通用的get-request
     *
     * @param url       请求路径
     * @param headerMap 请求头key-value
     * @return
     * @throws Exception
     */
    private Request commonGetRequest(String url, Map<String, String> headerMap) throws Exception {
        Request.Builder builder = new Request.Builder();
 
        Request request;
        if (headerMap != null && headerMap.keySet() != null && headerMap.keySet().size() > 0) {
            Headers headers = Headers.of(headerMap);
            request = builder.get()
                    .url(url)
                    .headers(headers)
                    .build();
        } else {
            request = builder.get()
                    .url(url)
                    .build();
        }
        return request;
    }
 
    private Request.Builder commonPostBuilder(String url, Map<String, String> headerMap) throws Exception {
        Request.Builder builder;
        if (headerMap != null && headerMap.keySet() != null && headerMap.keySet().size() > 0) {
            Headers headers = Headers.of(headerMap);
            builder = new Request.Builder()
                    .url(url)
                    .headers(headers);
        } else {
            builder = new Request.Builder()
                    .url(url);
        }
        return builder;
    }
 
 
    /**
     * get请求
     *
     * @param url       请求url
     * @param headerMap 请求头map
     * @return 结果字符串
     */
    public String get(String url, Map<String, String> headerMap) throws Exception {
        Request request = commonGetRequest(url, headerMap);
 
        Response response;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            log.error("发送同步-get请求发生异常:url={} ", e.fillInStackTrace());
        }
        return null;
    }
 
    /**
     * post请求
     *
     * @param url         请求Url
     * @param headerMap   请求头map
     * @param contentType 请求内容类型
     * @param data        请求体数据-对象序列化后的字符串格式数据
     * @return 结果字符串
     */
    public String post(String url, Map<String, String> headerMap, String contentType, String data) throws Exception {
        Request.Builder builder = commonPostBuilder(url, headerMap);
 
        Request request;
        RequestBody requestBody;
        if (data!=null && contentType!=null) {
            requestBody = RequestBody.create(MediaType.parse(contentType), data);
            request = builder.post(requestBody).build();
        } else {
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            request = builder.post(bodyBuilder.build()).build();
        }
 
        Response response;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * post请求--无请求体
     *
     * @param url 请求Url
     * @return 结果字符串
     */
    public String post(String url) throws Exception {
        Request.Builder builder = new Request.Builder().url(url);
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        Request request = builder.post(bodyBuilder.build()).build();
 
        Response response;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * post请求
     *
     * @param url
     * @param headerMap
     * @param bodyParams 请求体数据-map格式
     * @return
     * @throws Exception
     */
    public String post(String url, Map<String, String> headerMap, Map<String, String> bodyParams) throws Exception {
        Request.Builder builder = commonPostBuilder(url, headerMap);
 
        RequestBody body = setRequestBody(bodyParams);
        Request request = builder
                .post(body)
                .url(url)
                .build();
 
        Response response;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * post请求
     *
     * @param params
     * @return 备注:form表单提交
     */
    private RequestBody setRequestBody(Map<String, String> params) {
        RequestBody body = null;
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null && params.keySet() != null && params.keySet().size() > 0) {
            String key;
            Iterator<String> iterator = params.keySet().iterator();
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formBuilder.add(key, params.get(key));
            }
        }
        body = formBuilder.build();
 
        return body;
    }
 
    /**
     * 
     * @param url
     * @param params 参数
     * @param headMap 请求头
     * @return
     */
    public static String httpGet(String url, Map<String, Object> params, Map<String, String> headMap) {
        // 设置HTTP请求参数
        String result = null;
        url += getParams(params);
        String string=null;
        Headers setHeaders = SetHeaders(headMap);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).headers(setHeaders).build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            string = response.body().string();
        } catch (Exception e) {
            log.error("调用三方接口出错", e);
        }
        return string;
    }

    public static String getParams(Map<String, Object> params) {
        StringBuffer sb = new StringBuffer("?");
        if (params.size()>0) {
            for (Map.Entry<String, Object> item : params.entrySet()) {
                Object value = item.getValue();
                if (value!=null&&value!="") {
                    sb.append("&");
                    sb.append(item.getKey());
                    sb.append("=");
                    sb.append(value);
                }
            }
            return sb.toString();
        } else {
            return "";
        }
    }

    public static Headers SetHeaders(Map<String, String> headersParams) {
        Headers headers = null;
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        if (headersParams.size()>0) {
            Iterator<String> iterator = headersParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                headersbuilder.add(key, headersParams.get(key));
            }
        }
        headers = headersbuilder.build();
        return headers;
    }

}

调用

@RequestMapping("/getText3")
    public String getText(String name,String password){
        User user = new User(name, password);


        try {
            //去调用的dubbo中server服务的http测试接口路径
            String url="http://127.0.0.1:9013/v1/record/text3";
            java.util.Map<String,String> headerMap=new HashMap<>();
            //参数类型,我接口提供者接受的是json
            headerMap.put("Content-Type","application/json");
            HttpService httpService = new HttpService();
            String res = httpService.post(url,headerMap,"application/json"
                    ,objectMapper.writeValueAsString(user));

            log.info("响应结果:{} ",res);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

<!-- okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.1.2</version>
</dependency>

2021-11-22封装二:

package com.weiguanjishu.common;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.Request.Builder;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author tiger
 */
  <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.9</version>
        </dependency>
/*

  <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>
    使用如:        
        String url = "http://www.csdn.net/";
        Map<String, String> headers=new HashMap<>();
        Map<String, String> params=new HashMap<>();
        OkHttpUtil.httpGet(url,headers,params);

*/

@Slf4j
public class OkHttpUtil {

    private static OkHttpUtil instance;
    private static OkHttpClient client;

    private static MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");
    private static MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");

    private static final Integer connTimeout = 10000;
    private static final Integer readTimeout = 10000;
    private static final Integer writeTime = 20000;

    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(connTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTime, TimeUnit.MILLISECONDS)
                .sslSocketFactory(createSslSocketFactory(), x509TrustManager())
                .connectionPool(createConnectionPool())
                .build();
    }

    public static OkHttpUtil getInstance() {

        if (instance == null) {
            instance = new OkHttpUtil();
        }

        return instance;
    }

    /**
     * 设置连接池
     * 1.最大等待连接数
     * 2.连接时间
     */
    private static ConnectionPool createConnectionPool() {
        return new ConnectionPool(400, 5000, TimeUnit.MILLISECONDS);
    }


    /**
     * 信任所有证书
     */
    private static X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };

    }

    /**
     * HTTPS证书验证套接字工厂
     */
    private static SSLSocketFactory createSslSocketFactory() {
        SSLSocketFactory sslSocketFactory = null;
        try {
            // 信任所有链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslSocketFactory;
    }

    /***
     *  Get请求
     */
    public static String httpGet(String url, Map<String, String> headers, Map<String, String> params) {
        Response response = null;
        String res = "";
        log.info("[HttpGet start] URL:{}", url);
        if (url == null || url.isEmpty()) {
            throw new RuntimeException("请求地址不能为空");
        }

        StringBuffer buffer = new StringBuffer(url);
        Builder builder = new Builder();

        try {
            // 添加header
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // 请求参数
            if (params != null && !params.isEmpty()) {
                boolean flag = true;
                Iterator iterator = params.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();

                    if (flag) {
                        buffer.append("?" + entry.getKey() + "=" + entry.getValue());
                        flag = false;
                    } else {
                        buffer.append("&" + entry.getKey() + "=" + entry.getValue());
                    }
                }
            }

            log.info("[HttpGet start] URL:{}", buffer);
            Request request = builder.url(buffer.toString()).get().build();
            log.info("[HttpGet finish] URL:{}", request);
            response = client.newCall(request).execute();
            res = response.body().string();
        } catch (IOException var1) {
            log.error("[HttpGet Exception] URL:{}, error:{}", url, var1);
            throw new RuntimeException(var1);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return res;
    }

    /***
     *  POST  form表单请求
     */
    public static String postForm(String url, Map<String, String> headers, Map<String, String> params) {
        log.info("[HttpPost start] URL:{}", url);

        FormBody.Builder formBody = new FormBody.Builder();
        String result = null;

        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                formBody.add(key, params.get(key));
            }
        }
        RequestBody body = formBody.build();
        Builder request = new Builder();
        request.url(url).addHeader("CONTENT_TYPE", FORM_TYPE.toString()).build();

        // 添加请求头参数
        if (headers != null && !headers.isEmpty()) {
            Iterator iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request r = request.post(body).build();
        Response response = null;
        try {
            response = client.newCall(r).execute();
            ResponseBody responseBody = response.body();

            result = responseBody.string();
            log.info("[HttpPost FORM FINISH] RESULT: {}", result);
        } catch (IOException var2) {
            log.error("[HttpPost FORM Exception] URL:{}, error:{}", url, var2);
            throw new RuntimeException(var2);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return result;
    }

    /***
     *  POST JSON 请求,自定义超时配置
     */
    public static Response postForm(String url, String message, Map<String, String> headers) {
        return httpPost(url, message, headers, 5000, 5000, 5000);
    }


    public static Response httpPost(String url, String message, Map<String, String> headers, Integer connTimeout, Integer readTimeout, Integer writeTime) {
        RequestBody body = RequestBody.create(JSON_TYPE, message);
        Builder builder = new Builder();
        builder.url(url).post(body).addHeader("Accept", "application/json").build();

        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                builder.addHeader(header.getKey(), header.getValue());
            }
        }
        Request request = builder.build();
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(connTimeout, TimeUnit.MILLISECONDS).readTimeout(readTimeout, TimeUnit.MILLISECONDS).writeTimeout(writeTime, TimeUnit.MILLISECONDS).build();
        try {
            Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /***
     *  POST JSON 请求
     */
    public static String post(String url, String message, Map<String, String> headers) {
        RequestBody requestBody = RequestBody.create(JSON_TYPE, message);
        Builder builder = new Builder();
        builder.url(url).post(requestBody).build();
        Response response = null;
        String result = "";
        try {
            // 添加header
            if (headers != null && !headers.isEmpty()) {
                Iterator iterator = headers.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    builder.addHeader((String) entry.getKey(), (String) entry.getValue());
                }
            }
            Request request = builder.build();
            response = client.newCall(request).execute();
            if (response.code() == 200) {
                result = response.body() == null ? "" : response.body().string();
            }


        } catch (IOException var3) {
            log.error("[HttpPost JSON Exception] URL:{}, error:{}", url, var3);
            throw new RuntimeException(var3);

        } finally {
            if (response != null) {
                response.close();
            }
        }

        return result;
    }

}

2022-4-2原生用法:

简单使用方法:
首先,如果要设置设置超时时间和缓存,要通过OkHttpClient.Builder来设置

OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
OkHttpClient okHttpClient=builder.build();

get请求:

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
    .url(url)
    .build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
 
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
		System.out.println(response.body().string());
            }
        });

response的body有很多种输出方法,string()只是其中之一,注意是string()不是toString()。如果是下载文件就是response.body().bytes()。
另外可以根据response.code()获取返回的状态码。
post请求:
post提交普通的表单:如登录.

OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
    .add("键", "值")
    .add("键", "值")
    .build();
Request request = new Request.Builder()
    .url(url)
    .post(body)
    .build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {...}

RequestBody的数据格式都要指定Content-Type,常见的有三种:
application/x-www-form-urlencoded 数据是个普通表单
multipart/form-data 数据里有文件
application/json 数据是个json
上边的普通表单并没有指定Content-Type,这是因为FormBody继承了RequestBody,它已经指定了数据类型为application/x-www-form-urlencoded。

post提交json数据:

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, "你的json数据");
Request request = new Request.Builder()
    .url(url)
    .post(body)
    .build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {...}
post上传文件:
先定义上传文件类型:
public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
 
OkHttpClient okHttpClient = new OkHttpClient();
 File file = new File("/sdcard/xxx.txt");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                .build();
call.enqueue(new Callback() {...}

post上传文件并传入其他类型的字段:

public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
OkHttpClient okHttpClient = new OkHttpClient();
 File file = new File("/sdcard/xxx.txt");
RequestBody requestBody = new MultipartBody.Builder()
            .addFormDataPart("token","token")
            .addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();
Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
call.enqueue(new Callback() {...}

异步下载:

	OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
 
            }
 
            @Override
            public void onResponse(Call call, Response response) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(new File("/sdcard/xx.txt"));
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
               }
           }
       });

上面的都为异步请求,当然也支持同步的方式,同步的只要调用 call.execute()就可以了。

okhttp3的简单封装:

public class OkHttpClientManager {
    private static OkHttpClientManager mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mDelivery;
    private Gson mGson;
 
    private OkHttpClientManager()
    {
         OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
	okHttpClient.connectTimeout(5, TimeUnit.SECONDS);
        okHttpClient.readTimeout(5, TimeUnit.SECONDS);
        okHttpClient.cookieJar(new CookieJar() {
            private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url, cookies);
            }
 
            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                return null;
            }
        });
        mOkHttpClient=okHttpClient.build();
        mDelivery = new Handler(Looper.getMainLooper());
        mGson = new Gson();
    }
 
    public static OkHttpClientManager getInstance()
    {
        if (mInstance == null)
        {
            synchronized (OkHttpClientManager.class)
            {
                if (mInstance == null)
                {
                    mInstance = new OkHttpClientManager();
                }
            }
        }
        return mInstance;
    }
 
     /**
     * 异步的get请求
     *
     * @param url
     * @param callback
     */
    private void _getAsyn(String url, final ResultCallback callback)
    {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        deliveryResult(callback, request);
    }
 
    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     * @param params
     */
    private void _postAsyn(String url, final ResultCallback callback, Param... params)
    {
        Request request = buildPostRequest(url, params);
        deliveryResult(callback, request);
    }
 
    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     * @param params
     */
    private void _postAsyn(String url, final ResultCallback callback, Map<String, String> params)
    {
        Param[] paramsArr = map2Params(params);
        Request request = buildPostRequest(url, paramsArr);
        deliveryResult(callback, request);
    }
 
 private Param[] map2Params(Map<String, String> params)
    {
        if (params == null) return new Param[0];
        int size = params.size();
        Param[] res = new Param[size];
        Set<Map.Entry<String, String>> entries = params.entrySet();
        int i = 0;
        for (Map.Entry<String, String> entry : entries)
        {
            res[i++] = new Param(entry.getKey(), entry.getValue());
        }
        return res;
    }
 
 //*************对外公布的方法************
 
    //异步get请求
    public static void getAsyn(String url, ResultCallback callback)
    {
        getInstance()._getAsyn(url, callback);
    }
    //异步的post请求
    public static void postAsyn(String url, final ResultCallback callback, Param... params)
    {
        getInstance()._postAsyn(url, callback, params);
    }
 
    //异步的post请求
    public static void postAsyn(String url, final ResultCallback callback, Map<String, String> params)
    {
        getInstance()._postAsyn(url, callback, params);
    }
 
private void deliveryResult(final ResultCallback callback, Request request)
    {
        mOkHttpClient.newCall(request).enqueue(new Callback()
        {
 
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callback,e);
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try
                {
                    final String string = response.body().string();
                    if (callback.mType == String.class)
                    {
                        sendSuccessCallBack(callback,string);
                    } else
                    {
                        Object o = mGson.fromJson(string, callback.mType);
                        sendSuccessCallBack(callback,string);
                    }
 
                } catch (IOException e)
                {
                    sendFailCallback(callback,e);
                } catch (com.google.gson.JsonParseException e)//Json解析的错误
                {
                    sendFailCallback(callback,e);
                }
            }
        });
    }
private void sendFailCallback(final ResultCallback callback, final Exception e) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }
 
    private void sendSuccessCallBack(final ResultCallback callback, final Object obj) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onSuccess(obj);
                }
            }
        });
    }
 
    private Request buildPostRequest(String url, Param[] params)
    {
        if (params == null)
        {
            params = new Param[0];
        }
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        for (Param param : params)
        {
            formBodyBuilder.add(param.key, param.value);
        }
        RequestBody requestBody = formBodyBuilder.build();
        return new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }
public static abstract class ResultCallback<T>
    {
        Type mType;
 
        public ResultCallback()
        {
            mType = getSuperclassTypeParameter(getClass());
        }
 
        static Type getSuperclassTypeParameter(Class<?> subclass)
        {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class)
            {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }
 
        /**
         * 请求成功回调
         * @param response
         */
        public abstract void onSuccess(T response);
 
        /**
         * 请求失败回调
         * @param e
         */
        public abstract void onFailure(Exception e);
    }
 
    /**
     * post请求参数类
     */
    public static class Param
    {
        public Param()
        {
        }
 
        public Param(String key, String value)
        {
            this.key = key;
            this.value = value;
        }
        String key;
        String value;
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值