java对接第三方接口

Java (16) 2024-03-18 17:23

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说java对接第三方接口,希望能够帮助你!!!。

1.准备与第三方接口对接的账号

配置到了Apollo上面

java对接第三方接口_https://bianchenghao6.com/blog_Java_第1张

    @Value("${taofake.appId}")
	private String appId;
	@Value("${taofake.url}")
	private String url;
	@Value("${taofake.appSecret}")
	private String appSecret;

2.准备用于接受接口返回结果的实体类java对接第三方接口_https://bianchenghao6.com/blog_Java_第2张

3.准备发HTTP请求的工具类

java对接第三方接口_https://bianchenghao6.com/blog_Java_第3张
java对接第三方接口_https://bianchenghao6.com/blog_Java_第4张

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.调用第三方接口

黄色线表示访问第三方接口

java对接第三方接口_https://bianchenghao6.com/blog_Java_第5张

现在我们可以来测试一下了

java对接第三方接口_https://bianchenghao6.com/blog_Java_第6张

与第三方接口对接就完成了

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

发表回复