本文共 8196 字,大约阅读时间需要 27 分钟。
在软件开发过程中,第三方接口是非常常见的需求之一。通过本文,我们将详细介绍如何规范调用第三方接口,并提供一个实际项目中的实现案例。
在调用第三方接口之前,必须仔细阅读并理解接口规范文档。文档通常包含以下内容:
请求参数需要按照接口文档的要求进行格式化传输。通常包括以下几种类型:
/users/{id}。pageSize=10 或 order_by=created_at。返回参数的规范同样重要,通常包含以下内容:
400 表示请求错误,500 表示服务器错误。在实际项目中,通常会开发一个通用的工具类来处理第三方接口的调用。以下是一个典型的工具类实现:
package cn.stylefeng.guns.core.util;import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;import cn.stylefeng.roses.kernel.model.exception.ServiceException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;/** * 调用第三方接口工具类 */public class HttpUtil { private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); public static String doPost(String url, String requestBody) throws Exception { return doPost(url, requestBody, "application/json; charset=UTF-8", "POST", "UTF-8"); } public static String doPost(String url, String requestBody, String contentType, String requestMethod, String charset) throws Exception { StringBuffer buffer = new StringBuffer(); InputStream inputStream = null; OutputStream outputStream = null; BufferedReader reader = null; OutputStreamWriter writer = null; URL urlObject = null; HttpURLConnection connection = null; try { urlObject = new URL(url); connection = (HttpURLConnection) urlObject.openConnection(); connection.setRequestMethod(requestMethod); connection.setRequestProperty("Accept", contentType); connection.setRequestProperty("Charset", charset); connection.setRequestProperty("Content-Type", contentType); connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(300000); connection.setReadTimeout(300000); connection.connect(); outputStream = connection.getOutputStream(); writer = new OutputStreamWriter(outputStream, charset); writer.write(requestBody); writer.flush(); writer.close(); checkResponseCode(connection.getResponseCode()); inputStream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream, charset)); while ((line = reader.readLine()) != null) { buffer.append(line); } } catch (Exception e) { throw e; } finally { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } if (connection != null) { connection.disconnect(); } } return buffer.toString(); } public static String doGet(String url, String charset) throws Exception { return doGet(url, "application/json; charset=" + charset, charset); } public static String doGet(String url, String contentType, String charset) throws Exception { BufferedReader in = null; HttpURLConnection conn = null; try { url = dealUrlParameter(url, charset); URL realUrl = new URL(url); conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Charset", charset); conn.setRequestProperty("Accept-Charset", charset); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", contentType); conn.setConnectTimeout(300000); conn.setReadTimeout(300000); conn.setUseCaches(false); checkResponseCode(conn.getResponseCode()); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); StringBuilder builderLine = new StringBuilder(); String line; while ((line = in.readLine()) != null) { builderLine.append(line); } logger.debug(builderLine.toString()); String var8 = builderLine.toString(); return var8; } catch (Exception var17) { logger.error(var17.toString()); throw var17; } finally { try { if (conn != null) { conn.disconnect(); } if (in != null) { in.close(); } } catch (IOException var16) { var16.printStackTrace(); } } } public static String dealUrlParameter(String url, String charset) throws IOException { int parameterIndex = url.indexOf("?"); if (parameterIndex == -1) { return url; } else { String parameter = url.substring(parameterIndex + 1); String[] parameterArray = parameter.split("&"); StringBuffer newParameter = new StringBuffer(); String[] var6 = parameterArray; int var7 = parameterArray.length; for (int var8 = 0; var8 < var7; ++var8) { String kv = var6[var8]; String[] keyValue = kv.split("="); String vlaue = keyValue.length == 2 && keyValue[1] != null ? URLEncoder.encode(keyValue[1], charset) : ""; if (newParameter.length() == 0) { newParameter.append(keyValue[0]).append("=").append(vlaue); } else { newParameter.append("&").append(keyValue[0]).append("=").append(vlaue); } } return url.substring(0, parameterIndex) + "?" + newParameter; } } public static void checkResponseCode(int responseCode) { if (responseCode < 400) { logger.info("请求交互成功"); } else if (responseCode < 500) { if (responseCode == 429) { throw new ServiceException(BizExceptionEnum.REQUEST_NULL); } else { throw new ServiceException(BizExceptionEnum.REQUEST_NULL); } } else { throw new ServiceException(BizExceptionEnum.SERVER_ERROR); } }} 在本地service层,需要定义接口并实现其调用。以下是一个典型的示例:
/** * @Author ${USER} * @Description 添加人脸推送 * @Date 16:21 2020/4/10 * @Param list 参数列表 * @return_string 返回结果 */String pushAddFace(List 在service层实现接口的调用。以下是一个典型的实现示例:
@Overridepublic String pushAddFace(List
在控制器中集成第三方接口的调用。以下是一个典型的实现示例:
// 调用第三方接口List
调用第三方接口的过程与本地接口的调用类似。在service层定义接口,并实现其调用。在控制器中集成业务逻辑,调用相应的接口。通过规范化接口文档和使用通用工具类,可以简化接口调用的开发过程,提高开发效率。
转载地址:http://pdhfk.baihongyu.com/