### PriceQuery usage example Source: https://github.com/kuaidi100-api/java-demo Shows how to call PriceQuery.resolution with a PriceQueryParam. Sets kuaidicom to CompanyConstant.SF, sendAddr, recAddr, and weight (double). Prints the combos list containing product prices on success. ```java PriceQueryParam param = new PriceQueryParam(); param.setKuaidicom(CompanyConstant.SF); param.setSendAddr("广东省深圳市南山区"); param.setRecAddr("北京市朝阳区"); param.setWeight(1.0); Result result = new PriceQuery().resolution(param); if (result != null && result.isSuccess()) { System.out.println(result.getData().getCombos()); // 各产品价格 } ``` -------------------------------- ### Subscribe method usage example Source: https://github.com/kuaidi100-api/java-demo Builds a SubscribeReq with schema and param JSON, then calls subscribe. The response is SubscribeResp; returns null if non-200 or empty body. ```java SubscribeParameters sp = new SubscribeParameters(); sp.setCallbackurl("https://your-domain.com/callback?orderId=123"); sp.setPhone("17725390266"); sp.setResultv2("4"); SubscribeParam p = new SubscribeParam(); p.setCompany(CompanyConstant.SF); p.setNumber("SF3297600239259"); p.setKey(key); p.setParameters(sp); SubscribeReq req = new SubscribeReq(); req.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA); req.setParam(new Gson().toJson(p)); SubscribeResp resp = new Subscribe().subscribe(req); ``` -------------------------------- ### callBackUrl usage example Source: https://github.com/kuaidi100-api/java-demo Handles the push callback by verifying the signature. Returns null if signature mismatch; otherwise returns a JSON response with result true, returnCode 200, and message '成功'. ```java // 控制器中(示意),返回给快递100的应答体 SubscribeResp resp = new Subscribe().callBackUrl(param, sign); if (resp == null) { // 签名不一致,忽略本次推送 } else { return new Gson().toJson(resp); // {"result":true,"returnCode":"200","message":"成功"} } ``` -------------------------------- ### International shipment order usage example Source: https://github.com/kuaidi100-api/java-demo Complete example of placing an international shipment order. Builds a ShipmentReq with partner credentials, sender info, and package details, then creates a PrintReq with signature and calls client.shipment. Sets timeout to 10 seconds as recommended for international labels. Prints the tracking number and label URL on success. ```java ShipmentReq shipmentReq = new ShipmentReq(); shipmentReq.setPartnerId(""); shipmentReq.setPartnerKey(""); shipmentReq.setPartnerSecret(""); shipmentReq.setCode(""); shipmentReq.setKuaidicom("fedex"); shipmentReq.setCargo("invoice"); shipmentReq.setExpType("FedEx International First®"); shipmentReq.setUnitOfMeasurement("SU"); shipmentReq.setWeight(50.00); shipmentReq.setCustomsValue(1000.00); ManInfo sendMan = new ManInfo(); sendMan.setName("test"); sendMan.setMobile("16888888888"); sendMan.setCountryCode("CN"); sendMan.setCity("SHENZHEN"); sendMan.setAddr("Kingdee Software Park"); sendMan.setZipcode("518057"); shipmentReq.setSendMan(sendMan); PackageInfo pkg = new PackageInfo(); pkg.setLength(10.00); pkg.setWidth(20.00); pkg.setHeight(10.00); pkg.setWeight(50.00); shipmentReq.setPackageInfos(Collections.singletonList(pkg)); String param = new Gson().toJson(shipmentReq); String t = String.valueOf(System.currentTimeMillis()); PrintReq printReq = new PrintReq(); printReq.setKey(key); printReq.setMethod(ApiInfoConstant.ELECTRONIC_ORDER_PIC_METHOD); printReq.setSign(SignUtils.printSign(param, t, key, secret)); printReq.setParam(param); printReq.setT(t); InternationalShipment client = new InternationalShipment(); client.setTimeOut(1000, 10000); // 国际面单耗时较长,调大读取超时 try { ShipmentResp resp = client.shipment(printReq); if (resp != null) { System.out.println(resp.getKuaidinum()); System.out.println(resp.getLabel().getUrl()); // 面单文件 } } catch (Exception e) { // 网络异常 / 接口失败 } ``` -------------------------------- ### Store authorization request example Source: https://github.com/kuaidi100-api/java-demo Builds a StoreAuthReq with shopType, callbackUrl, and salt, serializes it to JSON, signs the request, and executes it via ThirdPlatformStoreAuth. Prints the authorizeUrl from the response if the HTTP status is 200. ```java StoreAuthReq storeAuthReq = new StoreAuthReq(); storeAuthReq.setShopType(ThirdPlatformConstant.TAO_BAO); storeAuthReq.setCallbackUrl("http://www.baidu.com"); storeAuthReq.setSalt("12345678"); String param = new Gson().toJson(storeAuthReq); PrintReq printReq = new PrintReq(); printReq.setKey(key); printReq.setSign(SignUtils.sign(param + key + secret)); printReq.setParam(param); HttpResult result = new ThirdPlatformStoreAuth().execute(printReq); if (result.getStatus() == 200 && result.getBody() != null) { ThirdPlatformBaseResp resp = new Gson().fromJson( result.getBody(), new TypeToken>() {}.getType()); System.out.println(resp.getData().getAuthorizeUrl()); } ``` -------------------------------- ### AutoNum usage example with AutoNumReq Source: https://github.com/kuaidi100-api/java-demo Shows how to call getComByNumList and getFirstComByNum with an AutoNumReq containing a tracking number and key. The catch block handles business failures where e.getMessage() includes returnCode and message. ```java AutoNumReq req = new AutoNumReq(); req.setNum("YT9383342193097"); req.setKey(key); try { List list = new AutoNum().getComByNumList(req); String first = new AutoNum().getFirstComByNum(req); } catch (Exception e) { // 业务失败,e.getMessage() 包含 returnCode 与 message } ``` -------------------------------- ### SendSms request example with SendSmsReq Source: https://github.com/kuaidi100-api/java-demo Shows how to build a SendSmsReq with callback, content (JSON), phone, seller, userid, tid, and sign (generated via SignUtils.smsSign). Then calls sendSms and stores the response. The sign is required and derived from key and userid. ```java SendSmsReq req = new SendSmsReq(); req.setCallback("http://www.baidu.com"); Map content = new HashMap<>(); content.put("code", "123456"); req.setContent(new Gson().toJson(content)); req.setPhone("15994708912"); req.setSeller("贵司名称"); req.setUserid(userid); req.setTid(tid); req.setSign(SignUtils.smsSign(key, userid)); SendSmsResp resp = new SendSms().sendSms(req); ``` -------------------------------- ### QueryTrackMap usage example Source: https://github.com/kuaidi100-api/java-demo Shows how to call QueryTrackMap via execute(QueryTrackReq) and parse the HttpResult body into QueryTrackMapResp using Gson. The response contains a trailUrl. ```java IBaseClient client = new QueryTrackMap(); HttpResult result = client.execute(queryTrackReq); QueryTrackMapResp resp = new Gson().fromJson(result.getBody(), QueryTrackMapResp.class); System.out.println(resp.getTrailUrl()); ``` -------------------------------- ### PrintImg usage example Source: https://github.com/kuaidi100-api/java-demo Shows how to call printImG and then getBase64Img to obtain image data URLs. The first image (imgs.get(0)) can be used directly as an . Requires a PrintReq with method ApiInfoConstant.ELECTRONIC_ORDER_PIC_METHOD ("getPrintImg") and business parameters PrintImgParam (extends PrintCommonReq, includes tempid, asyn, callBackUrl, and sender/receiver fields). ```java PrintBaseResp resp = new PrintImg().printImG(printReq); if (resp != null && resp.isResult() && resp.getData() != null) { List imgs = new PrintImg().getBase64Img(resp.getData().getImgBase64()); // imgs.get(0) 可直接作为 } ``` -------------------------------- ### Order commit task request example Source: https://github.com/kuaidi100-api/java-demo Builds a CommitTaskReq with shopType, shopId, orderStatus (using OrderStatus.UNSHIP.toString()), updateAtMin, updateAtMax, callbackUrl, and salt. Serializes it to JSON, signs the request, and executes it via ThirdPlatformOrderCommitTask. ```java CommitTaskReq req = new CommitTaskReq(); req.setShopType(ThirdPlatformConstant.TAO_BAO); req.setShopId("21231"); req.setOrderStatus(OrderStatus.UNSHIP.toString()); req.setUpdateAtMin("2022-02-17 16:00:00"); req.setUpdateAtMax("2022-02-17 16:30:00"); req.setCallbackUrl("http://www.baidu.com"); req.setSalt("12345678"); String param = new Gson().toJson(req); PrintReq printReq = new PrintReq(); printReq.setKey(key); printReq.setSign(SignUtils.sign(param + key + secret)); printReq.setParam(param); HttpResult result = new ThirdPlatformOrderCommitTask().execute(printReq); ``` -------------------------------- ### Basic usage with IBaseClient and QueryTrack Source: https://github.com/kuaidi100-api/java-demo Shows calling execute via the interface type to get a raw HttpResult. Requires setting queryTrackReq fields (customer/sign/param) before execution; checks status 200 and prints the JSON body. ```java import com.kuaidi100.sdk.api.QueryTrack; import com.kuaidi100.sdk.core.IBaseClient; import com.kuaidi100.sdk.pojo.HttpResult; IBaseClient client = new QueryTrack(); // 构造请求:设置 queryTrackReq 的 customer/sign/param 字段 HttpResult result = client.execute(queryTrackReq); if (result.getStatus() == 200) { System.out.println(result.getBody()); // 原始 JSON 响应 } ``` -------------------------------- ### Clone the java-demo repository Source: https://github.com/kuaidi100-api/java-demo/blob/master/README.md Clone the official Kuaidi100 Java SDK demo repository from GitHub. ```bash # git clone https://github.com/kuaidi100-api/java-demo.git ``` -------------------------------- ### PropertiesReader 读取配置方法 Source: https://github.com/kuaidi100-api/java-demo 用于从 account.properties 读取配置项。get 返回字符串,getInteger 对非法值抛 NumberFormatException,getBoolean 对非法值返回 false,set 仅写入内存不落盘,add 直接调用 property.put。静态块加载失败时 get 返回 null。 ```java PropertiesReader.get("key"); // String,property.getProperty(key) PropertiesReader.getInteger("..."); // Integer,Integer.valueOf(get(key)),非法值抛 NumberFormatException PropertiesReader.getBoolean("..."); // Boolean,Boolean.valueOf(get(key)),非法值返回 false PropertiesReader.set("key", "value"); // 写入内存 Properties(不落盘) PropertiesReader.add("key", obj); // property.put(key, value) ``` -------------------------------- ### 订阅回调处理(callBackUrl) Source: https://github.com/kuaidi100-api/java-demo/blob/master/README.md 处理快递100订阅推送的回调接口。建议记录回调内容以便排查问题,通过签名校验确认请求来自快递100,校验通过后返回成功响应。 ```java public SubscribeResp callBackUrl(String param, String sign){ //建议记录一下这个回调的内容,方便出问题后双方排查问题 log.debug("快递100订阅推送回调结果|{}|{}",param,sign); //订阅时传的salt,没有可以忽略 String salt = ""; String ourSign = SignUtils.sign(param + salt); SubscribeResp subscribeResp = new SubscribeResp(); subscribeResp.setResult(Boolean.TRUE); subscribeResp.setReturnCode("200"); subscribeResp.setMessage("成功"); //加密如果相等,属于快递100推送;否则可以忽略掉当前请求 if (ourSign.equals(sign)){ //TODO 业务处理 return subscribeResp; } return null; } ``` -------------------------------- ### Add SDK dependency with Gradle Source: https://github.com/kuaidi100-api/java-demo/blob/master/README.md Add the Kuaidi100 SDK to a Gradle project using the implementation configuration. ```gradle dependencies { implementation 'com.github.kuaidi100-api:sdk:1.1.4' } ``` -------------------------------- ### QueryTrackMap - 快递查询地图轨迹 Source: https://github.com/kuaidi100-api/java-demo QueryTrackMap is a client for querying the map track of a shipment. It does not have a typed public method; users call the inherited execute(QueryTrackReq) method to get an HttpResult, then parse it into QueryTrackMapResp using Gson. ```APIDOC ## QueryTrackMap - 快递查询地图轨迹 ### Description QueryTrackMap is a client for querying the map track of a shipment. It does not have a typed public method; users call the inherited execute(QueryTrackReq) method to get an HttpResult, then parse it into QueryTrackMapResp using Gson. ### Method POST (implied by the API endpoint) ### Endpoint `https://poll.kuaidi100.com/poll/maptrack.do` ### Parameters #### Request Body - `queryTrackReq` (QueryTrackReq) - Required - The request object containing tracking information. ### Response #### Success Response (200) - `trailUrl` (String) - The URL for the map track. ### Request Example ```java IBaseClient client = new QueryTrackMap(); HttpResult result = client.execute(queryTrackReq); QueryTrackMapResp resp = new Gson().fromJson(result.getBody(), QueryTrackMapResp.class); System.out.println(resp.getTrailUrl()); ``` ``` -------------------------------- ### PackageInfo Source: https://github.com/kuaidi100-api/java-demo Package dimensions and reference for international shipments. ```APIDOC ## PackageInfo ### Description Package dimensions and reference for international shipments. ### Fields - `height` (Double) - Required - Height - `width` (Double) - Required - Width - `length` (Double) - Required - Length - `weight` (Double) - Required - Weight - `packageReference` (String) - Optional - Package reference ``` -------------------------------- ### executeToObject Source: https://github.com/kuaidi100-api/java-demo This method is not implemented and always returns null. Do not rely on its return value. ```APIDOC ## executeToObject(BaseRequest) ### Description This method is not implemented and always returns null. Do not rely on its return value. ### Method N/A (Java method) ### Endpoint N/A ### Parameters #### Method Parameters - **BaseRequest** - Required - The request object. ### Response #### Success Response - **null** - Always returns null. ``` -------------------------------- ### execute(BaseRequest request) Source: https://github.com/kuaidi100-api/java-demo 执行 HTTP POST 请求,将请求对象转换为表单参数并发送到指定 URL,返回原始 HTTP 响应封装。 ```APIDOC ## execute(BaseRequest request) ### Description 执行 HTTP POST 请求,将请求对象转换为表单参数并发送到指定 URL,返回原始 HTTP 响应封装。 ### Method POST ### Endpoint 由子类 getApiUrl 决定,见 endpoints.md ### Parameters #### Request Body - **request** (BaseRequest) - Required - 携带接口 URL 与表单参数的请求对象 ### Response #### Success Response - **HttpResult** - HTTP 响应封装(status、body、error) ### Request Example ```java IBaseClient client = new QueryTrack(); HttpResult result = client.execute(queryTrackReq); ``` ``` -------------------------------- ### LabelV2 类定义与接口方法 Source: https://github.com/kuaidi100-api/java-demo LabelV2 继承 BaseClient,所有方法共用接口地址 ApiInfoConstant.NEW_TEMPLATE_URL(https://api.kuaidi100.com/label/order),业务类型由 PrintReq.method 区分,由方法内部写入。方法包括 order、repeatPrint、custom、deliveryTime、backOrder、interceptOrder,均返回 Result,code=200 表示成功,HTTP 非 200 或 body 为空时返回 null。 ```java public class LabelV2 extends BaseClient { @Override public String getApiUrl(BaseRequest request) { return ApiInfoConstant.NEW_TEMPLATE_URL; } public Result order(PrintReq printReq) throws Exception{ ... } public Result repeatPrint(PrintReq printReq) throws Exception{ ... } public Result custom(PrintReq printReq) throws Exception{ ... } public Result deliveryTime(PrintReq printReq) throws Exception{ ... } public Result backOrder(PrintReq printReq) throws Exception{ ... } public Result interceptOrder(PrintReq printReq) throws Exception{ ... } } ``` -------------------------------- ### SubscribeWithMap.subscribe — 订阅(带地图) Source: https://github.com/kuaidi100-api/java-demo 订阅快递信息并附带地图轨迹功能。与 Subscribe 方法一致,但回调参数解析为 SubscribeWithMapPushParamResp(含地图 trailUrl 字段),接口地址为 http://poll.kuaidi100.com/pollmap。 ```APIDOC ## [POST] http://poll.kuaidi100.com/pollmap ### Description 订阅快递信息并附带地图轨迹功能。与 Subscribe 方法一致,但回调参数解析为 SubscribeWithMapPushParamResp(含地图 trailUrl 字段),接口地址为 http://poll.kuaidi100.com/pollmap。 ### Method POST ### Endpoint http://poll.kuaidi100.com/pollmap ### Parameters #### Request Body - **param** (string) - Required - 请求参数,包含订阅信息,回调时解析为 SubscribeWithMapPushParamResp(含 trailUrl 字段) - **sign** (string) - Required - 签名,SignUtils.sign(param + salt),salt 为空字符串 ### Response #### Success Response (200) - **returnCode** (string) - 返回状态码 - **message** (string) - 返回消息 - **result** (object) - 返回结果 #### Response Example ```json { "returnCode": "200", "message": "提交成功", "result": true } ``` ``` -------------------------------- ### ExpressPackage Source: https://github.com/kuaidi100-api/java-demo Express package information. Contains weight, volume, box number, name, temperature range, count, and sample type. ```APIDOC ## ExpressPackage ### Description Express package information. Contains weight, volume, box number, name, temperature range, count, and sample type. ### Fields - `weight` (String) - Required - Weight - `volume` (String) - Required - Volume - `boxNo` (String) - Required - Box number - `name` (String) - Required - Package name - `tempRangeMax` (String) - Required - Maximum temperature range - `tempRangeMin` (String) - Required - Minimum temperature range - `count` (String) - Required - Count - `sampleType` (String) - Required - Sample type ``` -------------------------------- ### Add SDK dependency with Maven Source: https://github.com/kuaidi100-api/java-demo/blob/master/README.md Add the Kuaidi100 SDK to a Maven project using the dependency block. ```xml com.github.kuaidi100-api sdk 1.1.4 ``` -------------------------------- ### setTimeOut(int connectTimeout, int socketTimeout) Source: https://github.com/kuaidi100-api/java-demo 设置当前客户端实例的连接超时和读取超时(毫秒)。 ```APIDOC ## setTimeOut(int connectTimeout, int socketTimeout) ### Description 设置当前客户端实例的连接超时和读取超时(毫秒)。 ### Parameters - **connectTimeout** (int) - Required - 连接超时(毫秒),默认 5000 - **socketTimeout** (int) - Required - 读取超时(毫秒),默认 5000 ### Response void ### Request Example ```java IBaseClient client = new InternationalShipment(); client.setTimeOut(1000, 10000); ``` ``` -------------------------------- ### register(PickupCodeRegisterParam param) Source: https://github.com/kuaidi100-api/java-demo 注册取件码服务。参数包括快递公司编码、快递单号、收件人手机号和回调地址。返回原始HTTP响应,可通过Result解析,data.taskId为任务ID。 ```APIDOC ## register(PickupCodeRegisterParam param) ### Description 注册取件码服务。参数包括快递公司编码、快递单号、收件人手机号和回调地址。返回原始HTTP响应,可通过Result解析,data.taskId为任务ID。 ### Method POST ### Endpoint https://api.kuaidi100.com/pickupCode/register ### Parameters #### Request Body - **kuaidicom** (String) - Required - 快递公司编码 - **kuaidinum** (String) - Required - 快递单号 - **receiverPhone** (String) - Required - 收件人手机号 - **callbackUrl** (String) - Required - 回调地址 ### Response #### Success Response (200) - **taskId** (String) - 任务ID ### Request Example ```java PickupCode pickupCodeApi = new PickupCode(key, secret); PickupCodeRegisterParam param = new PickupCodeRegisterParam(); param.setKuaidicom("yuantong"); param.setKuaidinum("YT2574351128070"); param.setReceiverPhone("17702536051"); param.setCallbackUrl("http://www.your-domain.com/callback"); HttpResult result = pickupCodeApi.register(param); if (result.getStatus() == HttpStatus.SC_OK && StringUtils.isNotBlank(result.getBody())) { Result resultObj = new Gson().fromJson( result.getBody(), new TypeToken>() {}.getType()); if (resultObj.getCode() == 200) { System.out.println("任务ID: " + resultObj.getData().getTaskId()); } else { System.out.println("业务失败: " + resultObj.getMessage()); } } ``` ``` -------------------------------- ### CloudPrintAttachment 类实现(execute 与 print 方法) Source: https://github.com/kuaidi100-api/java-demo CloudPrintAttachment 继承 BaseClient,覆写 execute 方法,要求入参为 CloudAttachmentReq,否则抛出 ClassCastException。execute 通过 HttpUtils.doPostFile 以 multipart/form-data 上传文件(表单字段名 file),URL 按 CLOUD_PRINT_URL 模板拼接。print 方法返回 PrintBaseResp>,method 建议使用 ApiInfoConstant.CLOUD_PRINT_ATTACHMENT_METHOD("imgOrder"),业务参数用 CloudPrintAttachmentParam。 ```java public class CloudPrintAttachment extends BaseClient { @Override public String getApiUrl(BaseRequest request) { return null; } @Override public HttpResult execute(BaseRequest request) throws Exception{ if (request instanceof CloudAttachmentReq){ CloudAttachmentReq cloudPrintAttachmentReq = (CloudAttachmentReq)request; String url = String.format(ApiInfoConstant.CLOUD_PRINT_URL, cloudPrintAttachmentReq.getMethod(), cloudPrintAttachmentReq.getT(), cloudPrintAttachmentReq.getKey(), cloudPrintAttachmentReq.getSign(), URLEncoder.encode(cloudPrintAttachmentReq.getParam(), "UTF-8")); return HttpUtils.doPostFile(url,cloudPrintAttachmentReq.getFile(),super.getConnectTimeout(),super.getSocketTimeout()); } throw new ClassCastException(); } public PrintBaseResp print(CloudAttachmentReq cloudPrintAttachmentReq) throws Exception{ ... } } ``` -------------------------------- ### getSocketTimeout() Source: https://github.com/kuaidi100-api/java-demo 返回当前读取超时毫秒数。 ```APIDOC ## getSocketTimeout() ### Description 返回当前读取超时毫秒数。 ### Response - **int** - 读取超时毫秒数,默认 5000 ``` -------------------------------- ### BaseResponse Source: https://github.com/kuaidi100-api/java-demo 基础响应类型,包含结果、消息、状态和数据。注意:IBaseClient.executeToObject 声明返回该类型,但 BaseClient 实现恒返回 null。 ```APIDOC ## BaseResponse ### Description 基础响应类型,包含结果、消息、状态和数据。注意:IBaseClient.executeToObject 声明返回该类型,但 BaseClient 实现恒返回 null。 ### Fields - **result** (boolean) - 结果 - **message** (String) - 消息 - **status** (String) - 状态 - **data** (T) - 数据 ``` -------------------------------- ### interceptOrder 请求示例(Java) Source: https://github.com/kuaidi100-api/java-demo 构造 InterceptOrderReq 并调用 LabelV2().interceptOrder(printReq) 实现订单拦截。注意返回类型声明为 Result,但实际解析泛型为 Result(源码存在不一致)。业务参数包括 orderId、kuaidicom、kuaidinum、partnerId、partnerKey、reason、interceptType、orderRole、interceptPayType、salt、callbackUrl 等。 ```java InterceptOrderReq io = new InterceptOrderReq(); io.setOrderId("123456789"); io.setKuaidicom(CompanyConstant.JT); io.setKuaidinum("JT12345678"); io.setPartnerId("12345678"); io.setPartnerKey("12345678"); io.setReason("测试拦截"); io.setInterceptType("MODIFY_ADDR"); io.setOrderRole("1"); io.setInterceptPayType("THIRDPARTY"); io.setSalt("kuaidi1000api@salt"); io.setCallbackUrl("http://api.kuaidi100.com/test/callback"); // param = Gson(io),其余同上 Result result = new LabelV2().interceptOrder(printReq); ``` -------------------------------- ### SameCityOrder - 同城配送 Source: https://github.com/kuaidi100-api/java-demo SameCityOrder 类用于同城配送业务,通过 execute(PrintReq) 发送请求。接口地址为 https://order.kuaidi100.com/sameCity/order。 ```APIDOC ## SameCityOrder - 同城配送 ### Description SameCityOrder 类用于同城配送业务,通过 execute(PrintReq) 发送请求。接口地址为 https://order.kuaidi100.com/sameCity/order。 ### Method POST ### Endpoint https://order.kuaidi100.com/sameCity/order ### Parameters #### Request Body - **param** (object) - Required - 业务参数,需以 JSON 放入 PrintReq.param,具体字段以快递100官方文档为准。 ### Response #### Success Response (200) - **url** (string) - 认证URL(AuthResp) - **taskId** (string) - 任务ID(OrderResp) - **com** (string) - 快递公司编码(OrderResp/QueryResp) - **orderId** (string) - 订单ID(OrderResp) - **fee** (string) - 费用(OrderResp) - **distance** (string) - 距离(OrderResp) - **kuaidiNum** (string) - 快递单号(OrderResp) - **courierName** (string) - 快递员姓名(QueryResp) - **courierPhone** (string) - 快递员电话(QueryResp) - **predictDeliveryTime** (string) - 预计送达时间(QueryResp) - **trailUrl** (string) - 轨迹URL(QueryResp) - **lat** (string) - 纬度(QueryResp) - **lng** (string) - 经度(QueryResp) - **status** (string) - 状态(QueryResp) - **num** (string) - 单号(QueryResp) ``` -------------------------------- ### 核心调用模式示例:QueryTrack 查询 Source: https://github.com/kuaidi100-api/java-demo 演示所有 API 客户端的统一调用模式:构造请求实体、序列化参数、生成签名、执行请求。使用 QueryTrack 客户端和 SignUtils.querySign 生成签名,调用 execute 发送 POST 请求。 ```java import com.google.gson.Gson; import com.kuaidi100.sdk.api.QueryTrack; import com.kuaidi100.sdk.core.IBaseClient; import com.kuaidi100.sdk.request.*; import com.kuaidi100.sdk.utils.SignUtils; IBaseClient client = new QueryTrack(); QueryTrackReq req = new QueryTrackReq(); QueryTrackParam param = new QueryTrackParam(); param.setCom("yuantong"); param.setNum("YT9383342193097"); param.setPhone("17725390266"); String paramJson = new Gson().toJson(param); req.setParam(paramJson); req.setCustomer(customer); // 账号信息 req.setSign(SignUtils.querySign(paramJson, key, customer)); HttpResult result = client.execute(req); // 或者 (new QueryTrack()).queryTrack(req) ``` -------------------------------- ### SignUtils.querySign Source: https://github.com/kuaidi100-api/java-demo Generates a signature for real-time query or subscription requests by concatenating the parameter, key, and customer, then applying the sign method. ```APIDOC ## SignUtils.querySign ### Description Generates a signature for real-time query or subscription requests by concatenating the parameter, key, and customer, then applying the sign method. ### Method querySign ### Signature `public static String querySign(String param, String key, String customer)` ### Parameters - **param** (String) - Required - The request parameter string. - **key** (String) - Required - The API key. - **customer** (String) - Required - The customer identifier. ### Returns - **String** - The generated signature. ``` -------------------------------- ### Subscribe class implementation Source: https://github.com/kuaidi100-api/java-demo Defines the Subscribe client with getApiUrl returning the subscribe endpoint, plus subscribe and callBackUrl methods. The subscribe method is at line 36 and callBackUrl at line 58. ```java public class Subscribe extends BaseClient { @Override public String getApiUrl(BaseRequest request) { return ApiInfoConstant.SUBSCRIBE_URL; } public SubscribeResp subscribe(SubscribeReq subscribeReq) throws Exception{ ... } public SubscribeResp callBackUrl(String param, String sign){ ... } } ``` -------------------------------- ### 处理电子面单图片 base64 字符串(getBase64Img) Source: https://github.com/kuaidi100-api/java-demo/blob/master/README.md 将电子面单图片接口返回的 JSON 数组字符串解析为 List,为每个 base64 字符串添加前缀 "data:image/png;base64," 并替换 "\\n" 为空字符串。 ```java public List getBase64Img(String imgBase64){ List stringList= new Gson().fromJson(imgBase64, new TypeToken>() {}.getType()); List base64Img = new ArrayList(); if (stringList != null && stringList.size()>0){ for (String s : stringList) { s = "data:image/png;base64,"+s.replace("\\n",""); base64Img.add(s); } } return base64Img; } ``` -------------------------------- ### executeToObject(BaseRequest request) Source: https://github.com/kuaidi100-api/java-demo 执行请求并返回 BaseResponse 对象。注意:当前实现直接返回 null,调用前请以 null 处理。 ```APIDOC ## executeToObject(BaseRequest request) ### Description 执行请求并返回 BaseResponse 对象。注意:当前实现直接返回 null,调用前请以 null 处理。 ### Method POST ### Endpoint 由子类 getApiUrl 决定,见 endpoints.md ### Parameters #### Request Body - **request** (BaseRequest) - Required - 携带接口 URL 与表单参数的请求对象 ### Response #### Success Response - **BaseResponse** - 响应对象(当前返回 null) ``` -------------------------------- ### order 方法调用示例 Source: https://github.com/kuaidi100-api/java-demo 演示电子面单下单流程:构造收寄件人 ManInfo、OrderReq 并设置参数,序列化 param,生成时间戳 t 和签名 sign(MD5(param+t+key+secret) 转大写),调用 LabelV2().order(printReq)。成功时打印运单号 kuaidinum,失败时输出 HTTP 失败或错误码与消息。 ```java ManInfo recMan = new ManInfo(); recMan.setName("张三"); recMan.setMobile("15999566666"); recMan.setPrintAddr("广东省深圳市南山区科技南十二路"); ManInfo sendMan = new ManInfo(); sendMan.setName("李四"); sendMan.setMobile("15999566666"); sendMan.setPrintAddr("北京市海淀区xxx路"); OrderReq orderReq = new OrderReq(); orderReq.setKuaidicom(CompanyConstant.ZJS); orderReq.setCount(1); orderReq.setSiid(siid); orderReq.setTempId("60f6c17c7c223700131d8bc3"); orderReq.setSendMan(sendMan); orderReq.setRecMan(recMan); orderReq.setPrintType(PrintType.CLOUD); String param = new Gson().toJson(orderReq); String t = String.valueOf(System.currentTimeMillis()); PrintReq printReq = new PrintReq(); printReq.setT(t); printReq.setKey(key); printReq.setSign(SignUtils.printSign(param, t, key, secret)); printReq.setParam(param); Result result = new LabelV2().order(printReq); if (result != null && result.isSuccess()) { System.out.println(result.getData().getKuaidinum()); } else { System.out.println(result == null ? "HTTP 失败" : result.getCode() + ":" + result.getMessage()); } ``` -------------------------------- ### query(PickupCodeQueryParam param) Source: https://github.com/kuaidi100-api/java-demo 查询取件码服务。参数包括快递公司编码、快递单号和收件人手机号。返回原始HTTP响应,可通过Result解析,data包含取件码、取件地址、取件站点和状态描述。 ```APIDOC ## query(PickupCodeQueryParam param) ### Description 查询取件码服务。参数包括快递公司编码、快递单号和收件人手机号。返回原始HTTP响应,可通过Result解析,data包含取件码、取件地址、取件站点和状态描述。 ### Method POST ### Endpoint https://api.kuaidi100.com/pickupCode/query ### Parameters #### Request Body - **kuaidicom** (String) - Required - 快递公司编码 - **kuaidinum** (String) - Required - 快递单号 - **receiverPhone** (String) - Required - 收件人手机号 ### Response #### Success Response (200) - **pickUpCode** (String) - 取件码 - **pickUpAddress** (String) - 取件地址 - **pickUpStation** (String) - 取件站点 - **statusDesc** (String) - 状态描述 ``` -------------------------------- ### corder/COrderReq Source: https://github.com/kuaidi100-api/java-demo Request object for C-end (consumer) order creation. ```APIDOC ## corder/COrderReq ### Description Request object for C-end (consumer) order creation. ### Fields - `kuaidicom` (String) - Required - Express company code - `recManName` (String) - Required - Receiver name - `recManMobile` (String) - Required - Receiver mobile - `recManPrintAddr` (String) - Required - Receiver printed address - `sendManName` (String) - Required - Sender name - `sendManMobile` (String) - Required - Sender mobile - `sendManPrintAddr` (String) - Required - Sender printed address - `cargo` (String) - Required - Cargo description - `weight` (String) - Required - Weight - `remark` (String) - Optional - Remark - `salt` (String) - Required - Salt for signature - `callBackUrl` (String) - Optional - Callback URL - `dayType` (String) - Optional - Day type - `pickupStartTime` (String) - Optional - Pickup start time - `pickupEndTime` (String) - Optional - Pickup end time - `payment` (String) - Optional - Payment method - `expType` (String) - Optional - Express type - `op` (String) - Optional - Operation - `pollCallBackUrl` (String) - Optional - Poll callback URL - `resultv2` (String) - Optional - Result version - `thirdOrderId` (String) - Optional - Third-party order ID ``` -------------------------------- ### ThirdPlatformBaseResp Source: https://github.com/kuaidi100-api/java-demo 第三方平台响应类型,包含结果、返回码、消息和数据。用于第三方平台店铺授权/提交任务/回传单号接口。 ```APIDOC ## ThirdPlatformBaseResp ### Description 第三方平台响应类型,包含结果、返回码、消息和数据。用于第三方平台店铺授权/提交任务/回传单号接口。 ### Fields - **result** (boolean) - 结果 - **returnCode** (int) - 返回码 - **message** (String) - 消息 - **data** (T) - 数据 ``` -------------------------------- ### 基本调用 QueryTrack 查询快递轨迹 Source: https://github.com/kuaidi100-api/java-demo 构造 QueryTrackReq,设置 param(QueryTrackParam 的 JSON 序列化)、customer 和 sign(由 SignUtils.querySign 生成)。调用 queryTrack 后,若 resp 非空则打印 state 和轨迹数据大小。 ```java // 基本调用 QueryTrackReq req = new QueryTrackReq(); QueryTrackParam p = new QueryTrackParam(); p.setCom(CompanyConstant.YT); p.setNum("YT9383342193097"); p.setPhone("17725390266"); String param = new Gson().toJson(p); req.setParam(param); req.setCustomer(customer); req.setSign(SignUtils.querySign(param, key, customer)); QueryTrackResp resp = new QueryTrack().queryTrack(req); if (resp != null) { System.out.println(resp.getState() + " / " + resp.getData().size()); } ``` -------------------------------- ### pickupCode/PickupCodeQueryParam Source: https://github.com/kuaidi100-api/java-demo Parameters for querying a pickup code. ```APIDOC ## pickupCode/PickupCodeQueryParam ### Description Parameters for querying a pickup code. ### Fields - `kuaidicom` (String) - Required - Express company code - `kuaidinum` (String) - Required - Express number - `receiverPhone` (String) - Required - Receiver phone ``` -------------------------------- ### BsameCityExpress 客户端 Source: https://github.com/kuaidi100-api/java-demo 同城寄件客户端类,继承 BaseClient,提供统一的 execute 方法。业务方法通过 PrintReq.method 区分,包括预下单查价、下单、预取消、取消、加小费。 ```APIDOC ## BsameCityExpress 客户端 ### Description 同城寄件客户端类,继承 BaseClient,提供统一的 execute 方法。业务方法通过 PrintReq.method 区分,包括预下单查价、下单、预取消、取消、加小费。 ### Method POST ### Endpoint `https://api.kuaidi100.com/bsamecity/order` ### Parameters #### Request Body - **key** (string) - Required - 授权码 - **sign** (string) - Required - 签名 - **t** (string) - Required - 时间戳 - **param** (string) - Required - 业务参数 JSON 字符串 - **method** (string) - Required - 业务方法,可选值:`price`、`order`、`precancel`、`cancel`、`addfee` ### Response #### Success Response (200) - 响应体可用 `BsamecityPriceResp` / `BsamecityOrderResp` 解析 ### Request Example ```java BsamecityOrderReq orderReq = new BsamecityOrderReq(); orderReq.setKuaidicom("shunfengtongcheng"); orderReq.setLbsType(2); orderReq.setRecManName("张三"); orderReq.setRecManMobile("12345678910"); orderReq.setRecManProvince("北京市"); orderReq.setRecManCity("北京市"); orderReq.setRecManDistrict("海淀区"); orderReq.setRecManAddr("学清嘉创大厦A座15层"); // ...sender 字段、weight、callbackUrl 等 String t = String.valueOf(System.currentTimeMillis()); String param = new Gson().toJson(orderReq); PrintReq printReq = new PrintReq(); printReq.setKey(key); printReq.setSign(SignUtils.printSign(param, t, key, secret)); printReq.setT(t); printReq.setParam(param); printReq.setMethod(ApiInfoConstant.PRICE); // 或 BSAMECITY_ORDER IBaseClient client = new BsameCityExpress(); HttpResult result = client.execute(printReq); ``` ``` -------------------------------- ### QueryTrackMap class implementation Source: https://github.com/kuaidi100-api/java-demo Defines the QueryTrackMap client that overrides getApiUrl to return the map track endpoint. No additional public methods are provided. ```java public class QueryTrackMap extends BaseClient { @Override public String getApiUrl(BaseRequest request) { return ApiInfoConstant.QUERY_MAP_VIEW_URL; } } ``` -------------------------------- ### PickupCode.query Source: https://github.com/kuaidi100-api/java-demo Queries a pickup code. This method is part of the PickupCode client class. ```APIDOC ## PickupCode.query ### Description Queries a pickup code. This method is part of the PickupCode client class. ### Method query ### Parameters No parameters documented. ### Response Returns pickup code information as per the response entity. ``` -------------------------------- ### PriceQuery class extending BaseClient Source: https://github.com/kuaidi100-api/java-demo Defines the PriceQuery API client. Overrides getApiUrl to return ApiInfoConstant.NEW_TEMPLATE_URL (https://api.kuaidi100.com/label/order). The resolution method takes a PriceQueryParam and returns Result. ```java public class PriceQuery extends BaseClient { @Override public String getApiUrl(BaseRequest request) { return ApiInfoConstant.NEW_TEMPLATE_URL; } public Result resolution(PriceQueryParam priceQueryParam) throws Exception{ ... } } ``` -------------------------------- ### SubscribeWithMap.callBackUrl Source: https://github.com/kuaidi100-api/java-demo Verifies the signature of a callback request. Returns null if the signature does not match, indicating the request is not from Kuaidi100. ```APIDOC ## SubscribeWithMap.callBackUrl(param, sign) ### Description Verifies the signature of a callback request. Returns null if the signature does not match, indicating the request is not from Kuaidi100. ### Method N/A (Java method) ### Endpoint N/A ### Parameters #### Method Parameters - **param** (String) - Required - The callback parameters. - **sign** (String) - Required - The signature to verify. ### Response #### Success Response - **String** - The callback response body if signature matches. #### Error Response - **null** - If signature does not match. ``` -------------------------------- ### Subscribe.callBackUrl Source: https://github.com/kuaidi100-api/java-demo Verifies the signature of a callback request. Returns null if the signature does not match, indicating the request is not from Kuaidi100. ```APIDOC ## Subscribe.callBackUrl(param, sign) ### Description Verifies the signature of a callback request. Returns null if the signature does not match, indicating the request is not from Kuaidi100. ### Method N/A (Java method) ### Endpoint N/A ### Parameters #### Method Parameters - **param** (String) - Required - The callback parameters. - **sign** (String) - Required - The signature to verify. ### Response #### Success Response - **String** - The callback response body if signature matches. #### Error Response - **null** - If signature does not match. ```