开发基础:OkHttpClient了解与封装

时间:2020-08-05 19:36:34 来源:

【摘要】 开发基础:OkHttpClient了解与封装考必过小编为大家整理了关于开发基础:OkHttpClient了解与封装的信息,希望可以帮助到大家!

开发基础:OkHttpClient了解与封装

标签:join   val   email   result   err   expect   oid   基本   tpc   

前言

实际工作中,用到了远程接口调用,在网上大致查了下,Java Rest接口调用目前使用基本的apache的HttpClient的较多,但是个人觉得HttpClient使用起来较为繁琐,冗余代码较多(个人观点),所以选择了使用量较多的OkHttpClient的方式,并基于此进行封装。方便在以后的工作与开发中使用。

实现

package com.nmmp.common.utils.http;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.nmmp.project.integration.harbor.domain.vo.HarborProjectVo;
import okhttp3.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jiangzhuang
 * @Email: [email protected]
 * @Date: 2020/7/21
 * @Desc: OKHttp Utils(Based on OKHttp 3.10.0)
 */
public class OKHttpUtils {

    private static Logger logger = LoggerFactory.getLogger(OKHttpUtils.class);

    private static OkHttpClient client = new OkHttpClient();

    /**
     * Get Query
     *
     * @param url
     * @param params
     * @param auth     authentication info, auth[0]: username, auth[1]: password
     * @return results
     */
    public static String Get(String url, Map<String,Object> params, String[] auth) throws IOException {
        // OKHttp Basic Auth
        final String credential = Credentials.basic(auth[0],auth[1]);
        // OKHttp Request
        Request request = new Request.Builder()
                        .header("Authorization",credential)
                        .url(getParams(url,params)).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            logger.info("OKHttp Get Url: "+ url +" Request Successfully! Code:"+response.code());
            return response.body() != null ? response.body().string() : null;
        }
        catch (SocketTimeoutException e){
            logger.error("OKHttp Post Request Timeout, Check Your Network Connective Please!");
            throw e;
        }
    }

    /**
     * Post Query
     *
     * @param url
     * @param params
     * @return
     */
    public static String Post(String url, Map<String,String> params, String[] auth) throws IOException {
        // OKHttp Basic Auth
        final String credential = Credentials.basic(auth[0],auth[1]);
        // OKHttp Request
        Request request = new Request.Builder()
                            .header("Authorization",credential).url(url)
                            .post(postFormParams(params)).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            logger.info("OKHttp Post Url: "+ url + " Request Successfully! Code: "+ response.body());
            return response.body() != null ? response.body().string() : null;
        }
        catch (SocketTimeoutException e){
            logger.error("OKHttp Post Request Timeout, Check Your Network Connective Please!");
            throw e;
        }
    }

    /**
     * Post Query
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String Post(String url, String jsonStr, String[] auth) throws IOException {
        // OKHttp Basic Auth
        final String credential = Credentials.basic(auth[0],auth[1]);
        // OKHttp Request
        Request request = new Request.Builder()
                            .header("Authorization",credential).url(url)
                            .post(postJsonParams(jsonStr)).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()){
                logger.error("OKHttp Post Request Failed! Params:\t"+jsonStr);
                throw new IOException("Unexpected code " + response);
            }

            logger.info("OKHttp Post Url: "+ url +" Request Successfully! Code: "+response.code());
            return response.body() != null ? response.body().string() : null;
        }
        catch (SocketTimeoutException e){
            logger.error("OKHttp Post Request Timeout, Check Your Network Connective Please!");
            throw e;
        }
    }

    /**
     * Delete Query
     *
     * @param url
     * @param auth      authentication info, auth[0]: username, auth[1]: password
     * @return
     */
    public static String Delete(String url, String[] auth) throws IOException {
        // OKHttp Basic Auth
        final String credentials = Credentials.basic(auth[0], auth[1]);
        // OKHttp Request
        Request request = new Request.Builder().header("Authorization",credentials)
                            .url(url).delete().build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()){
                logger.error("OKHttp Delete Request Failed! url:\t"+url);
                throw new IOException("Unexpected code " + response);
            }

            logger.info("OKHttp Delete Url: "+ url +" Request Successfully! Code:\t"+response.code());
            return response.body() != null ? response.body().string() : null;
        }
        catch (SocketTimeoutException e){
            logger.error("OKHttp Delete Request Timeout, Check Your Network Connective Please!");
            throw e;
        }
    }

    // --------------------------------------- Utils Private Method

    /**
     * Generate Get Urls From Map
     *
     * @param url       request url
     * @param params    request params
     * @return results
     */
    private static String getParams(String url, Map<String,Object> params){
        StringBuilder urlBuilder = new StringBuilder(url);

        if(params != null && !params.isEmpty()){
            urlBuilder.append("?").append(Joiner.on(‘&‘).withKeyValueSeparator(‘=‘).join(params));
        }

        return urlBuilder.toString();
    }

    /**
     * Generate Post Request Form Body From Map
     *
     * @param params
     * @return results
     */
    private static RequestBody postFormParams(Map<String,String> params){
        FormBody.Builder formBodyBuilder = new FormBody.Builder();

        if(!params.isEmpty()){
            params.forEach(formBodyBuilder::add);
        }

        return formBodyBuilder.build();
    }

    /**
     * Generate Post Request Json Body From Map
     *
     * @param jsonStr
     * @return results
     */
    private static RequestBody postJsonParams(String jsonStr){
        // POST Body Type
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        return RequestBody.create(JSON,jsonStr);
    }


    // --------------------------------------- Utils Test Method
    @Test
    public void GetUtilTest() throws IOException {
        String url = "http:192.168.1.171/api/projects";
        String[] auth = new String[]{"admin","Harbor12345"};
        Map<String,Object> map = new HashMap<>();

        /*map.put("name","library");*/

        String result = OKHttpUtils.Get(url, map, auth);

        System.out.println(result);
    }

    @Test
    public void PostJSONUtilTest() throws IOException {
        String url = "http:192.168.1.171/api/projects";
        String[] auth = new String[]{"admin","Harbor12345"};

        HarborProjectVo hpv = new HarborProjectVo();
        hpv.setProject_name("xxxxx");

        String result = OKHttpUtils.Post(url, JSON.toJSONString(hpv), auth);

        System.out.println(result);
    }

    @Test
    public void DeleteUtilTest() throws IOException {
        String url = "http:192.168.1.171/api/projects/39";
        String[] auth = new String[]{"admin","Harbor12345"};

        String response = OKHttpUtils.Delete(url, auth);

        logger.info(response);
    }
}

目前只提供了基本的方法与认证,如果存在问题或有更好的建议可以及时与我联系

开发基础:OkHttpClient了解与封装

标签:join   val   email   result   err   expect   oid   基本   tpc   

以上就是开发基础:OkHttpClient了解与封装的内容,更多资讯请及时关注考必过网站,最新消息小编会第一时间发布,大家考试加油!

上一篇      下一篇
前端相关推荐 更多>>
前端热点专题 更多>>
热点问答
国家公务员考试年龄限制是多少 公务员国考和省考考试内容有什么区别 函授大专学历能不能考公务员 国家公务员考试考点能自己选择吗 新闻学专业能报考2022年公务员考试吗 什么是联合培养研究生 什么是破格录取研究生 什么人不适合读研 研究生报名户口所在地填什么 研究生结业和毕业有什么区别
网站首页 网站地图 返回顶部
考必过移动版 https://m.kaobiguo.net