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();
//    /**
//     * 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 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 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 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 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 headerMap, Map 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 params) {
        RequestBody body = null;
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null && params.keySet() != null && params.keySet().size() > 0) {
            String key;
            Iterator 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 params, Map 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 params) {
        StringBuffer sb = new StringBuffer("?");
        if (params.size()>0) {
            for (Map.Entry 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 headersParams) {
        Headers headers = null;
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        if (headersParams.size()>0) {
            Iterator 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 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;
    }



    com.squareup.okhttp3
    okhttp
    3.1.2

你可能感兴趣的:(java工具笔记)