大家好,又见面了,我是你们的朋友全栈君。
1.准备与第三方接口对接的账号
配置到了Apollo上面
@Value("${taofake.appId}")
private String appId;
@Value("${taofake.url}")
private String url;
@Value("${taofake.appSecret}")
private String appSecret;
2.准备用于接受接口返回结果的实体类
3.准备发HTTP请求的工具类
http工具类
package cn.zhaocha.common.utils;
import java.io.IOException;
import java.util.Map;
import cn.zhaocha.vo.BaseResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
@Slf4j
public class OKHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OKHttpUtil.class);
private static OkHttpClient client = getClient();
public static OkHttpClient getClient() {
if (client == null) {
client = genericClient();// 创建OkHttpClient对象
}
return client;
}
public static OkHttpClient genericClient() {
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
// .addHeader("Content-Type", "text/html; charset=gb2312")
// .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
// .addHeader("Accept-Encoding", "gzip, deflate")
// .addHeader("Connection", "keep-alive")
// .addHeader("Accept", "*/*")
// .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 9.0.0; MI 6 Build/OPR1.170623.032; wv) AppleWebKit/537.36 (KHTML, like Gecko)
// Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36/Android/globalscanner/4.00")
// .addHeader("Accept-Language", "zh-CN,en-US;q=0.9")
.addHeader("ApiVersion", "1.0")
// .addHeader("X-Requested-With", "com.globalscanner")
.build();
return chain.proceed(request);
}
}).build();
return httpClient;
}
public static String postAsync(String urlStr, Map<String, String> paramMap, Callback callback) {
return postAsync(urlStr, paramMap, callback, null);
}
public static String postAsync(String urlStr, Map<String, String> paramMap, Callback callback, Map<String, String> header) {
Request.Builder oneBuilder = getOneBuilder(urlStr, paramMap, header);
Request request = oneBuilder.build();
getClient().newCall(request).enqueue(callback);
return null;
}
private static Request.Builder getOneBuilder(String urlStr, Map<String, String> paramMap, Map<String, String> header) {
// 创建表单请求体
FormBody.Builder formBody = new FormBody.Builder();
for (String key : paramMap.keySet()) {
formBody.add(key, paramMap.get(key));
}
// 创建Request 对象。//传递请求体
Request.Builder postBuild = new Request.Builder().url(urlStr).post(formBody.build());
if (header != null && header.size() > 0) {
for (String key : header.keySet()) {
postBuild.addHeader(key, header.get(key));
}
}
return postBuild;
}
private static Request.Builder getGetBuilder(String urlStr, Map<String, String> paramMap, Map<String, String> header) {
HttpUrl.Builder urlBuilder = HttpUrl.parse(urlStr).newBuilder();
if (paramMap != null) {
for (String key : paramMap.keySet()) {
urlBuilder.setQueryParameter(key, paramMap.get(key));
}
}
Request.Builder requestBuilder = new Request.Builder().url(urlBuilder.build())
.headers(header == null ? new Headers.Builder().build() : Headers.of(header)).get();
return requestBuilder;
}
/**
* 同步请求
*/
public static <T> BaseResponseVo<T> post(String urlStr, Map<String, String> paramMap, Class clazz) {
return post(urlStr, paramMap, null, clazz);
}
public static <T> BaseResponseVo<T> post(String urlStr, Map<String, String> paramMap, Map<String, String> header, Class clazz) {
Request.Builder oneBuilder = getOneBuilder(urlStr, paramMap, header);
Request request = oneBuilder.build();
try {
log.info("请求:OKHttpUtil-post-日志信息请求参数:" + urlStr + " " + paramMap.toString());
Response response = client.newCall(request).execute();
if (response != null && response.isSuccessful()) {
if (response.body() == null) {
log.info("响应:OKHttpUtil-post-日志信息响应结果未空:");
return BaseResponseVo.err("1", "response.body内容为空", null);
}
String content = response.body().string();
log.info("响应:OKHttpUtil-post-日志信息响应结果:" + content);
// String content ="{error_msg: \"成功\",error_code: 0}";
// String content = "{error_msg: \"失败\",error_code: 1}";
if (!StringUtils.isEmpty(content)) {
T obj = (T) FastJsonUtil.jsonToBean(content, clazz);
return BaseResponseVo.succ("0", "获取成功", obj);
}
}
} catch (IOException e) {
e.printStackTrace();
return BaseResponseVo.err(e.toString());
}
return BaseResponseVo.err("1", "获取失败", null);
}
public static <T> BaseResponseVo<T> get(String urlStr, Map<String, String> paramMap, Map<String, String> header, Class clazz) {
Request.Builder oneBuilder = getGetBuilder(urlStr, paramMap, header);
Request request = oneBuilder.build();
try {
log.info("请求:OKHttpUtil-post-日志信息请求参数:" + urlStr + " " + paramMap.toString());
Response response = client.newCall(request).execute();
if (response != null && response.isSuccessful()) {
if (response.body() == null) {
log.info("响应:OKHttpUtil-get-日志信息响应结果未空:");
return BaseResponseVo.err("1", "response.body内容为空", null);
}
String content = response.body().string();
log.info("响应:OKHttpUtil-get-日志信息响应结果:" + content);
if (!StringUtils.isEmpty(content)) {
T obj = (T) FastJsonUtil.jsonToBean(content, clazz);
return BaseResponseVo.succ("0", "获取成功", obj);
}
}
} catch (IOException e) {
e.printStackTrace();
return BaseResponseVo.err(e.toString());
}
return BaseResponseVo.err("1", "获取失败", null);
}
}
4.调用第三方接口
黄色线表示访问第三方接口
现在我们可以来测试一下了
与第三方接口对接就完成了
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/133282.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...