目录
第一步阿里云订阅快递服务
登录以后点击云市场找到对应的接口
找到一个免费的点击进去
点击免费使用
购买后点击这个买家控制台去看详情
点击进去api接口中
复制java代码到你的项目中,其他的也可以看一下成功的响应和失败的响应等
这个address代表入参参数
第二步整合springBoot将接口调通
原有的代码
public static void main(String[] args) {
String host = "https://kzaddress2.market.alicloudapi.com";
String path = "/api/address/parse";
String method = "POST";
String appcode = "你自己的AppCode";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求,定义相对应的Content-Type
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("address", "赵王17267365647秀洲区王江泾镇南元丰大道82282700");
try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
System.out.println(response.toString());
//获取response的body
//System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
}
改造后的代码
将代码拆分,先拆分一个config有助于管理,读取配置文件,这样可以提高代码的可读性,也可以方便后期的管理
package com.macro.mall.portal.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author:xsp
* @Description:
* @name:ApiConfig
* @Date:2024/10/22 22:29
*/
@Data
@Component
@ConfigurationProperties(prefix = "api")
public class ApiConfig {
private String host;
private String path;
private String method;
private String appcode;
}
在这里面我们需要改一下appcode吗
api:
host: https://kzaddress2.market.alicloudapi.com
path: /api/address/parse
method: POST
appcode: 你的appcode码
回到买家控制台找到你的appcode码改一下
然后工具类改成这样交给spring容器管理,用的时候直接注入就行了
package com.macro.mall.portal.util;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.macro.mall.model.UmsMemberReceiveAddress;
import com.macro.mall.portal.config.ApiConfig;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @Author:xsp
* @Description:
* @name:AddreInfoUtils
* @Date:2024/10/22 22:26
*/
@Component
public class AddressInfoUtils {
@Autowired
private ApiConfig apiConfig;
public UmsMemberReceiveAddress getAddressInfo(String address){
UmsMemberReceiveAddress umsMemberReceiveAddress = new UmsMemberReceiveAddress();
String host = apiConfig.getHost();
String path = apiConfig.getPath();
String method = apiConfig.getMethod();
String appcode = apiConfig.getAppcode();
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求,定义相对应的Content-Type
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("address", address);
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
System.out.println(response.toString());
String s = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = JSON.parseObject(s);
Integer code = jsonObject.getInteger("code");
if(code==200){
JSONObject data = jsonObject.getJSONObject("data");
if(data!=null){
umsMemberReceiveAddress.setDetailAddress(data.getString("detail"));
umsMemberReceiveAddress.setCity(data.getString("city"));
umsMemberReceiveAddress.setProvince(data.getString("province"));
umsMemberReceiveAddress.setRegion(data.getString("area"));
umsMemberReceiveAddress.setPostCode(data.getString("zipCode"));
umsMemberReceiveAddress.setName(data.getString("name"));
umsMemberReceiveAddress.setPhoneNumber(data.getString("mobile"));
return umsMemberReceiveAddress;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
在这里我也是封装一个对象用于接收返回的快递智能识别信息
package com.macro.mall.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
@Data
public class UmsMemberReceiveAddress implements Serializable {
private Long id;
private Long memberId;
@Schema(title = "收货人名称")
private String name;
private String phoneNumber;
@Schema(title = "是否为默认")
private Integer defaultStatus;
@Schema(title = "邮政编码")
private String postCode;
@Schema(title = "省份/直辖市")
private String province;
@Schema(title = "城市")
private String city;
@Schema(title = "区")
private String region;
@Schema(title = "详细地址(街道)")
private String detailAddress;
}
接下来开始测试了
@Autowired
private AddressInfoUtils addressInfoUtils;
@Operation(summary = "根据地址获取快递信息")
@GetMapping(value = "/getAddressInfo")
public UmsMemberReceiveAddress getAddressInfo() {
UmsMemberReceiveAddress addressInfo=addressInfoUtils.getAddressInfo("赵王17267365647秀洲区王江泾镇南元丰大道82282700");
return addressInfo;
}
这样就表示成功了
第三步对接前端进行渲染效果
后台
controller
/**
* 快递识别
* @param addressInfo 快递信息
*/
@Operation(summary = "快递识别")
@GetMapping("/identification/{addressInfo}")
@ResponseBody
public CommonResult identification(@PathVariable String addressInfo){
UmsMemberReceiveAddress umsMemberReceiveAddress=memberReceiveAddressService.identification(addressInfo);
return CommonResult.success(umsMemberReceiveAddress);
}
servie
/**
* 快递识别
* @param addressInfo 快递信息
*/
UmsMemberReceiveAddress identification(String addressInfo);
serviceImpl
@Autowired
private AddressInfoUtils addressInfoUtils;
/**
* 快递识别
* @param addressInfo 快递信息
*/
@Override
public UmsMemberReceiveAddress identification(String addressInfo) {
return addressInfoUtils.getAddressInfo(addressInfo);
}
前台
前台的我用的是uniapp做的(你们可以自行选择前段技术写,前端代码我写的不怎么好,仅供参考)
template部分
<template>
<view class="content">
<view class="row b-b">
<text class="tit">姓名</text>
<input class="input" type="text" v-model="addressData.name" placeholder="收货人姓名" placeholder-class="placeholder" />
</view>
<view class="row b-b">
<text class="tit">手机号码</text>
<input class="input" type="number" v-model="addressData.phoneNumber" placeholder="收货人手机号码" placeholder-class="placeholder" />
</view>
<view class="row b-b">
<text class="tit">邮政编码</text>
<input class="input" type="number" v-model="addressData.postCode" placeholder="收货人邮政编码" placeholder-class="placeholder" />
</view>
<!-- <view class="row b-b">
<text class="tit">所在区域</text>
<text @click="chooseLocation" class="input">
{{addressData.province}} {{addressData.city}} {{addressData.region}}
</text>
<text class="yticon icon-shouhuodizhi" @click="chooseLocation"></text>
</view> -->
<view class="row b-b">
<text class="tit">所在区域</text>
<input class="input" type="text" v-model="addressData.prefixAddress" placeholder="所在区域" placeholder-class="placeholder" />
</view>
<view class="row b-b">
<text class="tit">详细地址</text>
<input class="input" type="text" v-model="addressData.detailAddress" placeholder="详细地址" placeholder-class="placeholder" />
</view>
<br>
<br>
<view class="row b-b">
<text class="tit">快递识别</text>
<textarea
class="input1"
v-model="addressInfo"
placeholder="请输入您的快递信息"
placeholder-class="placeholder"
/>
<button @click="sure">确定</button>
</view>
<view class="row default-row">
<text class="tit">设为默认</text>
<switch :checked="addressData.defaultStatus==1" color="#fa436a" @change="switchChange" />
</view>
<button class="add-btn" @click="confirm">提交</button>
</view>
</template>
script部分
<script>
import {
addAddress,
updateAddress,
fetchAddressDetail,
address,
} from '@/api/address.js';
export default {
data() {
return {
addressInfo:'',
addressData: {
name: '',
phoneNumber: '',
postCode: '',
detailAddress: '',
default: false,
province: '',
city: '',
region: '',
prefixAddress: ''
}
}
},
onLoad(option) {
let title = '新增收货地址';
if (option.type === 'edit') {
title = '编辑收货地址'
fetchAddressDetail(option.id).then(response=>{
this.addressData = response.data;
this.addressData.prefixAddress = this.addressData.province+this.addressData.city+this.addressData.region;
});
}
this.manageType = option.type;
uni.setNavigationBarTitle({
title
})
},
methods: {
switchChange(e) {
this.addressData.defaultStatus = e.detail.value ? 1 : 0;
},
//地图选择地址
chooseLocation() {
uni.chooseLocation({
success: (data) => {
this.covertAdderss(data.address);
this.addressData.detailAddress = data.name;
}
})
},
//将地址转化为省市区
covertAdderss(address) {
console.log("covertAdderss", address);
if (address.indexOf("省") != -1) {
this.addressData.province = address.substr(0, address.indexOf("省") + 1);
address = address.replace(this.addressData.province, "");
this.addressData.city = address.substr(0, address.indexOf("市") + 1);
address = address.replace(this.addressData.city, "");
this.addressData.region = address.substr(0, address.indexOf("区") + 1);
} else {
this.addressData.province = address.substr(0, address.indexOf("市") + 1);
address = address.replace(this.addressData.province, "");
this.addressData.city = "";
this.addressData.region = address.substr(0, address.indexOf("区") + 1);
}
},
//快递识别
sure() {
address(this.addressInfo)
.then(res => {
this.addressData = res.data;
this.addressData.prefixAddress = res.data.province+res.data.city+res.data.region;
})
.catch(error => {
console.error("Error fetching address:", error);
// 处理错误,如提示用户
});
},
//提交
confirm() {
let data = this.addressData;
if (!data.name) {
this.$api.msg('请填写收货人姓名');
return;
}
if (!/(^1[3|4|5|7|8][0-9]{9}$)/.test(data.phoneNumber)) {
this.$api.msg('请输入正确的手机号码');
return;
}
if (!data.prefixAddress) {
this.$api.msg('请输入区域');
return;
}
this.covertAdderss(data.prefixAddress);
if (!data.province) {
this.$api.msg('请输入正确的省份');
return;
}
if (!data.detailAddress) {
this.$api.msg('请填写详细地址信息');
return;
}
if(this.manageType=='edit'){
updateAddress(this.addressData).then(response=>{
//this.$api.prePage()获取上一页实例,可直接调用上页所有数据和方法,在App.vue定义
this.$api.prePage().refreshList(data, this.manageType);
this.$api.msg("地址修改成功!");
setTimeout(() => {
uni.navigateBack()
}, 800)
});
}else{
addAddress(this.addressData).then(response=>{
//this.$api.prePage()获取上一页实例,可直接调用上页所有数据和方法,在App.vue定义
this.$api.prePage().refreshList(data, this.manageType);
this.$api.msg("地址添加成功!");
setTimeout(() => {
uni.navigateBack()
}, 800)
});
}
},
}
}
</script>
style部分
<style lang="scss">
page {
background: $page-color-base;
padding-top: 16upx;
}
.row {
display: flex;
align-items: center;
position: relative;
padding: 0 30upx;
height: 110upx;
background: #fff;
.tit {
flex-shrink: 0;
width: 150upx;
font-size: 30upx;
color: $font-color-dark;
}
.input {
flex: 1;
font-size: 30upx;
color: $font-color-dark;
}
.add-btn1 {
padding: 10px 20px;
background-color: #007aff;
color: white;
border: none;
border-radius: 4px;
}
.icon-shouhuodizhi {
font-size: 36upx;
color: $font-color-light;
}
}
.default-row {
margin-top: 16upx;
.tit {
flex: 1;
}
switch {
transform: translateX(16upx) scale(.9);
}
}
.input1 {
flex: 1;
height: 100px; /* 设置文本域的高度 */
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 10px;
resize: none; /* 禁用文本域的大小调整 */
}
.add-btn {
display: flex;
align-items: center;
justify-content: center;
width: 690upx;
height: 80upx;
margin: 60upx auto;
font-size: $font-lg;
color: #fff;
background-color: $base-color;
border-radius: 10upx;
box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
}
</style>
最终效果
最终我告诉大家,在对接第三方接口的时候基本就是这样子,所有的第三方接口基本一样的步骤,一定要找到切入点,看清楚接口文档,自己在拉过来第三方接口代码以后改造成适合项目风格的代码
标签:addressData,SpringBoot,api,private,快递,API,address,data,String From: https://blog.csdn.net/2301_81405087/article/details/143272199