springboot使用阿里云全球物流快递查询实现根据物流单号实时查询

1.需要去阿里云的网站注册,开通服务,申请结束后拿到AppCode
springboot使用阿里云全球物流快递查询实现根据物流单号实时查询_第1张图片
2.上代码

@Api(value = "aLi-wuliu", description = "")
@RestController
@RequestMapping("/api/aLiWuLiu")
public class ApiAliWuLiuController {
    //申请的appcode(授权码),在上图找到
    private static final String appcode = "*************";

    @ApiOperation("物流详情")
    @GetMapping(value = "/list")
    public Object list(String shipNumber) throws Exception {
        String host = "https://goexpress.market.alicloudapi.com";
        String path = "/goexpress";
        String method = "GET";
        Map headers = new HashMap();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map querys = new HashMap();
        querys.put("no", shipNumber.trim());
        // querys.put("type", "zto");

        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        //获取response的body
        String ss = EntityUtils.toString(response.getEntity());
       //返回json格式
        return JSONObject.fromObject(ss);
    }
}

3.工具类HttpUtils

package com.navi.user.util;


import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HttpUtils {

    /**
     * get
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method,
                                     Map headers,
                                     Map querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map headers,
                                      Map querys,
                                      Map bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List nameValuePairList = new ArrayList();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map headers,
                                      Map querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map headers,
                                      Map querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Put String
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map headers,
                                     Map querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Put stream
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map headers,
                                     Map querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map headers,
                                        Map querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

4.到这个时候代码就已经结束了
使用swagger测试
返回值:

{
	"code": "OK",
	"no": "780098068058",
	"type": "ZTO",
	"list": [{
		"content": "【石家庄市】 快件已在 【长安三部】 签收,签收人: 本人, 感谢使用中通快递,期待再次为您服务!",
		"time": "2018-03-09 11:59:26"
	}, {
		"content": "【石家庄市】 快件已到达 【长安三部】(0311-85344265),业务员 容晓光(13081105270) 正在第1次派件, 请保持电话畅通,并耐心等待",
		"time": "2018-03-09 09:03:10"
	}, {
		"content": "【石家庄市】 快件离开 【石家庄】 发往 【长安三部】",
		"time": "2018-03-08 23:43:44"
	}, {
		"content": "【石家庄市】 快件到达 【石家庄】",
		"time": "2018-03-08 21:00:44"
	}, {
		"content": "【广州市】 快件离开 【广州中心】 发往 【石家庄】",
		"time": "2018-03-07 01:38:45"
	}, {
		"content": "【广州市】 快件到达 【广州中心】",
		"time": "2018-03-07 01:36:53"
	}, {
		"content": "【广州市】 快件离开 【广州花都】 发往 【石家庄中转】",
		"time": "2018-03-07 00:40:57"
	}, {
		"content": "【广州市】 【广州花都】(020-37738523) 的 马溪 (18998345739) 已揽收",
		"time": "2018-03-07 00:01:55"
	}],
	"state": "3",  /* -1:单号或代码错误;0:暂无轨迹;1:快递收件;2:在途中;3:签收;4:问题件 5.疑难件 6.退件签收 */
	"msg": "查询成功",
	"name": "中通快递",                 /*  快递公司名称                */  
	"site": "www.zto.com",              /*  快递公司官网                */
	"phone": "95311",                   /*  快递公司电话                */
	"courier": "容晓光",                /*  快递员 或 快递站(没有则为空)*/
        "courierPhone":"13081105270",       /*  快递员电话 (没有则为空)     */
        "updateTime":"2019-08-27 13:56:19", /*  快递轨迹信息最新时间        */
        "takeTime":"2天20小时14分",         /*  发货到收货消耗时长 (截止最新轨迹)  */
	"logo": "https://img3.fegine.com/express/zto.jpg"      /*  快递Logo  */
}

错误码 错误信息 描述
201 快递单号错误 快递单号错误
203 快递公司不存在 快递公司不存在
204 快递公司识别失败 快递公司识别失败
205 没有信息 没有信息
207 该单号被限制,错误单号 该单号被限制,错误单号
-1 单号或快递公司错误 单号或快递公司错误
OK 查询成功 查询成功

你可能感兴趣的:(SpringBoot,物流跟踪)