okHttp3 请求类封装

0.pom依赖

 <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp-urlconnection</artifactId>
      <version>3.3.1</version>
 </dependency>

1.实体类


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zjy.iot.commom.api.haiKang.entity.CloudEyesApiResponse;
import com.zjy.zjeframework.common.extension.RestResult;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CloudEyesRequestService {

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(5000, TimeUnit.MILLISECONDS).readTimeout(5000, TimeUnit.MILLISECONDS).build();

    private static final MediaType FORM_CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");

    private static final String FORM_CONTENT_TYPE_STRING = "application/x-www-form-urlencoded";

    public static final String RESPONSE_CODE = "code";

    public static final Integer SUCCESS_CODE = 200;

    /**
     * 通过验证接口获取令牌
     *
     * @return token
     */
    public static String getTokenByAuthInterface() {
        String accessToken = null;
        final String clientId = "6ca9158d01ca4af483c7f3e3932158aa";
        final String clientSecret = "6c6070a4600d48a390b952005755d9f5";
        final String path = REQUEST_HOST + "/oauth/token";
        FormBody formBody = new FormBody.Builder()
                .add("client_id", clientId)
                .add("client_secret", clientSecret)
                .add("grant_type", "client_credentials")
                .add("scope", "app")
                .build();
        Request formRequest = new Request.Builder()
                .post(formBody).url(path)
                .build();
        try {
            Response formResponse = HTTP_CLIENT.newCall(formRequest).execute();
            String resultString = formResponse.body().string();
            JSONObject result = JSON.parseObject(resultString);
            if (CloudEyesApiResponse.SUCCESS_STATUS.equals(result.getString(RESPONSE_CODE))) {
                accessToken = result.getString("access_token");
            }
            log.info("获取token结果:result={}", resultString);
        } catch (IOException e) {
            log.info("获取token失败:msg={}", e.getMessage());
        }
        return accessToken;
    }

    /**
     * get请求
     *
     * @param path   路径
     * @param params 参数
     * @param token  token
     * @return JSONObject
     */
    public static String normalGetRequest(String path, Map<String, Object> params, String token) {
        // 创建一个请求 Builder
        Request.Builder builder = new Request.Builder();
        // 创建一个 request
        Request request = builder.url(path).build();
        // 创建一个 HttpUrl.Builder
        HttpUrl.Builder urlBuilder = request.url().newBuilder();
        // 创建一个 Headers.Builder
        Headers.Builder headerBuilder = request.headers().newBuilder();
        // 装载请求头参数
        headerBuilder.add("Authorization", "bearer  " + token);
        headerBuilder.add("Content-Type", FORM_CONTENT_TYPE_STRING);
        // 装载请求的参数
        Iterator<Map.Entry<String, Object>> queryIterator = params.entrySet().iterator();
        queryIterator.forEachRemaining(e -> {
            urlBuilder.addQueryParameter(e.getKey(), e.getValue().toString());
        });
        // 设置自定义的 builder
        builder.url(urlBuilder.build()).headers(headerBuilder.build());
        try (Response formResponse = HTTP_CLIENT.newCall(builder.build()).execute()) {
            return formResponse.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过post方式请求
     *
     * @param path   路径
     * @param params 参数
     * @return Response
     */
    public static String normalPostRequest(String path, Map<String, Object> params, String token) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                builder.add(key, value.toString());
            }
        }
        FormBody formBody = builder.build();
        Request formRequest = new Request.Builder()
                .post(formBody).url(path)
                .addHeader("Authorization", "bearer  " + token)
                .build();
        try {
            Response formResponse = HTTP_CLIENT.newCall(formRequest).execute();
            if (SUCCESS_CODE == formResponse.code()) {
                return formResponse.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String normalPutRequest(String path, Map<String, Object> params, String token) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                builder.add(key, value.toString());
            }
        }
        FormBody formBody = builder.build();
        Request formRequest = new Request.Builder()
                .put(formBody).url(path)
                .addHeader("Authorization", "bearer  " + token)
                .build();
        try {
            Response formResponse = HTTP_CLIENT.newCall(formRequest).execute();
            if (SUCCESS_CODE == formResponse.code()) {
                return formResponse.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实体类转Map
     *
     * @param obj 实体对象
     * @return map
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 时间格式转换
     *
     * @param dateString 原始string
     * @return 带格式的字符串
     */
    public static String dateStringFormat(String dateString) {
        String result = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime hopeArriveTime = LocalDateTime.parse(dateString, formatter);
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = hopeArriveTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        result = simpleDateFormat.format(date);
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值