Java后端如何优雅地封装第三方API调用逻辑以对接美团外卖霸王餐接口
Java后端如何优雅地封装第三方API调用逻辑以对接美团外卖霸王餐接口在Java后端开发中对接第三方API如美团外卖霸王餐接口是常见的需求。直接在业务代码中拼接URL、处理JSON、写HTTP请求不仅导致代码臃肿还难以维护和测试。本文将介绍一种基于Spring Boot的优雅封装方案采用“客户端-请求-响应”分离的设计模式结合OkHttp作为底层HTTP客户端实现高内聚、低耦合的API调用逻辑。1. 引入依赖首先在pom.xml中引入必要的依赖包括Spring Web、OkHttp以及JSON处理库如Jackson或Fastjson。dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdcom.squareup.okhttp3/groupIdartifactIdokhttp/artifactIdversion4.9.3/version/dependencydependencygroupIdcom.alibaba/groupIdartifactIdfastjson/artifactIdversion1.2.83/version/dependency/dependencies2. 定义通用的数据传输对象为了统一处理API响应我们定义通用的请求和响应基类。API响应封装packagecom.baodanbao.cn.model;publicclassMeituanResponseT{privateintcode;privateStringmessage;privateTdata;// 构造函数publicMeituanResponse(){}publicMeituanResponse(intcode,Stringmessage,Tdata){this.codecode;this.messagemessage;this.datadata;}// Getter和SetterpublicintgetCode(){returncode;}publicvoidsetCode(intcode){this.codecode;}publicStringgetMessage(){returnmessage;}publicvoidsetMessage(Stringmessage){this.messagemessage;}publicTgetData(){returndata;}publicvoidsetData(Tdata){this.datadata;}publicbooleanisSuccess(){returnthis.code0;// 假设0为成功}}霸王餐活动请求对象packagecom.baodanbao.cn.model.request;publicclassBawangcanActivityRequest{privateStringappId;privatelongtimestamp;privateStringsign;privateActivityBodybody;// Getter和SetterpublicstaticclassActivityBody{privateStringshopId;privateintlimitCount;privateStringstartDate;privateStringendDate;// Getter和Setter}}3. 封装HTTP客户端创建一个专门的OkHttpClient Bean并配置超时、拦截器等。packagecom.baodanbao.cn.config;importokhttp3.OkHttpClient;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjava.util.concurrent.TimeUnit;ConfigurationpublicclassHttpClientConfig{BeanpublicOkHttpClientmeituanOkHttpClient(){returnnewOkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).writeTimeout(30,TimeUnit.SECONDS).build();}}4. 核心API客户端封装这是最核心的部分。我们创建一个MeituanBawangcanClient类专门负责与美团接口通信。packagecom.baodanbao.cn.client;importcom.alibaba.fastjson.JSON;importcom.baodanbao.cn.model.MeituanResponse;importcom.baodanbao.cn.model.request.BawangcanActivityRequest;importcom.baodanbao.cn.util.SignUtil;importokhttp3.*;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;importjava.io.IOException;ComponentpublicclassMeituanBawangcanClient{privatefinalOkHttpClienthttpClient;privatefinalStringappKey;privatefinalStringappSecret;privatefinalStringapiUrl;AutowiredpublicMeituanBawangcanClient(OkHttpClienthttpClient,Value(${meituan.app-key})StringappKey,Value(${meituan.app-secret})StringappSecret,Value(${meituan.api-url})StringapiUrl){this.httpClienthttpClient;this.appKeyappKey;this.appSecretappSecret;this.apiUrlapiUrl;}/** * 创建霸王餐活动 */publicMeituanResponseStringcreateActivity(BawangcanActivityRequest.ActivityBodybody)throwsIOException{// 1. 构建请求体BawangcanActivityRequestrequestnewBawangcanActivityRequest();request.setAppId(appKey);request.setTimestamp(System.currentTimeMillis()/1000);request.setBody(body);// 2. 生成签名重要StringjsonBodyJSON.toJSONString(request);StringsignSignUtil.generateSign(jsonBody,appSecret);request.setSign(sign);// 3. 序列化最终请求StringfinalJsonJSON.toJSONString(request);// 4. 构建HTTP请求RequesthttpRequestnewRequest.Builder().url(apiUrl/bawangcan/activity/create).post(RequestBody.create(finalJson,MediaType.get(application/json; charsetutf-8))).build();// 5. 执行调用try(ResponseresponsehttpClient.newCall(httpRequest).execute()){if(!response.isSuccessful())thrownewIOException(Unexpected code response);ResponseBodyresponseBodyresponse.body();if(responseBodynull)thrownewIOException(Empty response body);StringresultresponseBody.string();// 6. 解析响应returnJSON.parseObject(result,newTypeReferenceMeituanResponseString(){}.getType());}}}5. 签名工具类第三方API通常需要签名验证我们将签名逻辑独立出来。packagecom.baodanbao.cn.util;importjavax.crypto.Mac;importjavax.crypto.spec.SecretKeySpec;importjava.nio.charset.StandardCharsets;importjava.security.InvalidKeyException;importjava.security.NoSuchAlgorithmException;publicclassSignUtil{privatestaticfinalStringHMAC_SHA256HmacSHA256;publicstaticStringgenerateSign(Stringcontent,Stringsecret)throwsException{try{MacmacMac.getInstance(HMAC_SHA256);SecretKeySpecsecretKeySpecnewSecretKeySpec(secret.getBytes(StandardCharsets.UTF_8),HMAC_SHA256);mac.init(secretKeySpec);byte[]signDatamac.doFinal(content.getBytes(StandardCharsets.UTF_8));// 这里简化实际需要转为Hex字符串returnbytesToHex(signData);}catch(NoSuchAlgorithmException|InvalidKeyExceptione){thrownewException(签名生成失败,e);}}privatestaticStringbytesToHex(byte[]bytes){StringBuilderresultnewStringBuilder();for(byteb:bytes){result.append(String.format(%02x,b));}returnresult.toString();}}6. 在业务Service中使用封装完成后业务层代码变得非常简洁清晰。packagecom.baodanbao.cn.service;importcom.baodanbao.cn.client.MeituanBawangcanClient;importcom.baodanbao.cn.model.MeituanResponse;importcom.baodanbao.cn.model.request.BawangcanActivityRequest;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;ServicepublicclassMarketingService{AutowiredprivateMeituanBawangcanClientmeituanClient;publicStringlaunchBawangcanCampaign(StringshopId,intlimit){try{BawangcanActivityRequest.ActivityBodybodynewBawangcanActivityRequest.ActivityBody();body.setShopId(shopId);body.setLimitCount(limit);// ... 设置其他参数MeituanResponseStringresponsemeituanClient.createActivity(body);if(response.isSuccess()){return活动创建成功ID: response.getData();}else{returnAPI调用失败: response.getMessage();}}catch(Exceptione){e.printStackTrace();return系统异常;}}}7. 配置文件示例在application.yml中配置美团相关的参数。meituan:app-key:your_app_key_hereapp-secret:your_app_secret_hereapi-url:https://openapi.meituan.com本文著作权归 俱美开放平台 转载请注明出处
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2468876.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!