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;
}
}