最近开发使用了很多微服务,如:支付宝、微信支付、短信网关、快递100,极光推送等。今天就讲下快递100的使用,简单易懂,废话不多说,直接上代码。
使用步骤:
1、引入commons-httpclient-3.1.jar以及commons-codec-1.6.jar网络编程必备;
2、去官网申请一个账号,免费版的只有一个key-授权密钥,企业版有customer-快递100给客户的编号,key-授权密钥,区别就是花钱的没有限制次数。
3、开始编写代码。
4、查询工具类:
package com.mes.util;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.ibatis.common.logging.Log;
import com.ibatis.common.logging.LogFactory;
import com.kz.order.web.controller.HttpRequest;
import com.mes.kuaidi100.util.MD5;
/*
-
饿汉式单例模式
/
public class KuaiDi100Util {
/*- 日志
/
public Log logger = LogFactory.getLog(KuaiDi100Util.class);
/* - 私有化构造器,方式外部通过类创建对象
*/
private KuaiDi100Util() {
}
private static final KuaiDi100Util instance = new KuaiDi100Util();// 创建对象
// 提供一个静态的公共方法,供外部访问,返回该类的对象
public static KuaiDi100Util getInstance() {
return instance;
}
/**- 免费版调用方式
- @param key
- @param com
- @param nu
- @return
*/
public String getKuaiDiInfo4Free(String key, String com, String nu) {
String content = "";
try {
URL url = new URL("http://www.kuaidi100.com/api?id=" + key + "&com=" + com + "&nu=" + nu+"&valicode="+0);
URLConnection con = url.openConnection();
con.setAllowUserInteraction(false);
InputStream urlStream = url.openStream();
byte b[] = new byte[10000];
int numRead = urlStream.read(b);
content = new String(b, 0, numRead);
while (numRead != -1) {
numRead = urlStream.read(b);
if (numRead != -1) {
// String newContent = new String(b, 0, numRead);
String newContent = new String(b, 0, numRead, "UTF-8");
content += newContent;
}
}
urlStream.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("快递查询错误");
}
return content;
}
/**
企业版调用方式(实时查询,订阅查询需要将数据保存到数据库)
@param param
customer 快递100给客户的编号
key 授权密钥
-
@return
*/
public List<Map<Object, Object>> getKuaiDiInfo4Firm(String param) {
List<Map<Object, Object>> orderList = new ArrayList<Map<Object, Object>>();String customer = "";
String key = "";
String sign = MD5.encode(param + key + customer);
HashMap<String, String> params = new HashMap<String, String>();
params.put("param", param);
params.put("sign", sign);
params.put("customer", customer);
String resp;
try {
resp = new HttpRequest().postData("http://poll.kuaidi100.com/poll/query.do", params, "utf-8").toString();// 格式化数据 JSONObject reslut = JSONObject.fromObject(resp); JSONArray kuaidiList = (JSONArray) reslut.get("data"); if (kuaidiList != null && kuaidiList.size() > 0) { for (int i = 0; i < kuaidiList.size(); i++) { JSONObject jobj = JSONObject.fromObject(kuaidiList.get(i)); Map<Object, Object> map = new HashMap<Object, Object>(); map.put("time", jobj.get("ftime")); map.put("context", jobj.get("context")); orderList.add(map); } }
} catch (Exception e) {
e.printStackTrace();
logger.error("快递查询错误");
}
return orderList;
}
//测试
public static void main(String[] args) {
String emsCode ="shentong";
String emsCompCode ="3311699385987";
String param ="{"com":""+emsCode+"","num":""+emsCompCode+""}";
List<Map<Object, Object>> result = KuaiDi100Util.getInstance().getKuaiDiInfo4Firm(param);
System.out.println(result.toString());
}
}
- 日志
5、使用到的MD5加密方法:
public final static String encode(String s) {
try {
byte[] btInput = s.getBytes();
// 使用指定的字节更新摘要
getMdInst().update(btInput);
// 获得密文
byte[] md = getMdInst().digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
6、httpRequest类:
package com.kz.order.web.controller;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpRequest {
public static String addUrl(String head, String tail) {
if (head.endsWith("/")) {
if (tail.startsWith("/")) {
return head.substring(0, head.length() - 1) + tail;
} else {
return head + tail;
}
} else {
if (tail.startsWith("/")) {
return head + tail;
} else {
return head + "/" + tail;
}
}
}
public synchronized static String postData(String url, Map<String, String> params, String codePage) throws Exception {
final HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(25 * 1000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(30 * 1000);
final PostMethod method = new PostMethod(url);
if (params != null) {
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, codePage);
method.setRequestBody(assembleRequestParams(params));
}
String result = "";
try {
httpClient.executeMethod(method);
result = new String(method.getResponseBody(), codePage);
} catch (final Exception e) {
throw e;
} finally {
method.releaseConnection();
}
return result;
}
public synchronized static String postData(String url, String codePage) throws Exception {
final HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);
final GetMethod method = new GetMethod(url);
String result = "";
try {
httpClient.executeMethod(method);
result = new String(method.getResponseBody(), codePage);
} catch (final Exception e) {
throw e;
} finally {
method.releaseConnection();
}
return result;
}
/**
* 组装http请求参数
*
* @param params
* @param menthod
* @return
*/
private synchronized static NameValuePair[] assembleRequestParams(Map<String, String> data) {
final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
nameValueList.add(new NameValuePair((String) entry.getKey(), (String) entry.getValue()));
}
return nameValueList.toArray(new NameValuePair[nameValueList.size()]);
}
}
7、效果图:
8、详情见快递100官网http://www.kuaidi100.com/