public class ExpressQueryTextHandler extends DefaultMessageHandler {
@Override
public boolean canDo(Map<String, String> requestMap) {
String content = requestMap.get("Content").trim();
String msgType = requestMap.get("MsgType");
return MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType) && content.startsWith("快递");
}
@Override
public BaseMessage handleByMe(Map<String, String> requestMap) {
String expressQuery = requestMap.get("Content").trim();
String[] tokens = expressQuery.split("@");//快递@快递公司@单号
if (tokens.length!=3) {
return MessageFactory.createTextMessage(fromUserName, toUserName, ContentUtil.getExpressUsage());
}
return MessageFactory.createTextMessage(fromUserName, toUserName,
ExpressQueryService.getExpress(tokens[1], tokens[2]));
}
@Test
public void testHandleMessage(){
Map<String, String> requestMap = new HashMap<String, String>();
requestMap.put("FromUserName", "dfgsd");
requestMap.put("ToUserName", "dfsfd");
requestMap.put("MsgType", MessageUtil.REQ_MESSAGE_TYPE_TEXT);
requestMap.put("Content", "快递@"+"中通@"+"360387762616");
BaseMessage message = new ExpressQueryTextHandler().handleMessage(requestMap);
System.out.println(MessageUtil.messageToXml(message));
}
}
public static String getExpressUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("快递查询操作指南").append("\n\n");
buffer.append("回复:快递@快递公司@快递单号").append("\n");
buffer.append("回复“?/?”显示主菜单");
return buffer.toString();
}
/**
* 快递查询
* 爱快递http://www.aikuaidi.cn/rest/?key=ff4735a30a7a4e5a8637146fd0e7cec9&order={$keyword}&id=shentong&show=xml
* @author 熊诗言
*
*/
public class ExpressQueryService {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//配置申请的KEY
public static final String APPKEY ="2fcf423df0bff251751c02179187b7b4";
//1.快递查询API
@SuppressWarnings("unchecked")
public static String getExpress(String companyName,String expressNum){
String companyNum = getCompanyByName(companyName);
String result =null;
String url ="http://v.juhe.cn/exp/index";//请求接口地址
Map<String, Object> params = new HashMap<String, Object>();//请求参数
params.put("com",companyNum);//需要查询的快递公司编号
params.put("no",expressNum);//需要查询的订单号
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
params.put("dtype","json");//返回数据的格式,xml或json,默认json
StringBuffer buffer = new StringBuffer();
buffer.append("快递:"+companyName+"\n");
buffer.append("快递单号:"+expressNum+"\n");
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
object = object.getJSONObject("result");
JSONArray array = object.getJSONArray("list");
List<ExpressInfo> list = JSONArray.toList(array, new ExpressInfo() , new JsonConfig());
for (ExpressInfo expressInfo : list) {
buffer.append(expressInfo.getDatetime()).append(expressInfo.getRemark()).append("\n");
}
return buffer.toString();
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
}catch (Exception e) {
e.printStackTrace();
}
return "对不起,未查询到此快递";
}
/**
* [{"com":"顺丰","no":"sf"},{"com":"申通","no":"sto"},{"com":"圆通","no":"yt"},{"com":"韵达","no":"yd"},{"com":"天天","no":"tt"},{"com":"EMS","no":"ems"},{"com":"中通","no":"zto"},{"com":"汇通","no":"ht"},{"com":"全峰","no":"qf"}]
*/
//2.快递公司编号对照表
@SuppressWarnings("unchecked")
private static String getCompanyByName(String name){
String result =null;
String url ="http://v.juhe.cn/exp/com";//请求接口地址
Map<String, Object> params = new HashMap<String, Object>();//请求参数
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
List<CompanyPair> list = JSONArray.toList(object.getJSONArray("result"),
new CompanyPair(), new JsonConfig());
for (CompanyPair companyPair : list) {
if (companyPair.getCom().equals(name)) {
return companyPair.getNo();
}
}
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
private static String net(String strUrl, Map<String, Object> params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
strUrl = strUrl+"?"+urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try{
DataOutputStream out = new DataOutputStream(
conn.getOutputStream());
out.writeBytes(urlencode(params));
}catch (Exception e) {
// TODO: handle exception
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
//将map型转为请求参数型
public static String urlencode(Map<String, ?> data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, ?> i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static void main(String[] args) {
String info = getExpress("中通", "360387762616");
System.out.println(info);
}
}
public class CompanyPair{
private String com;
private String no;
。。。。
}
public class ExpressInfo {
private String datetime;
private String remark;
private String zone;
。。。。
}
@Override
public boolean canDo(Map<String, String> requestMap) {
String content = requestMap.get("Content").trim();
String msgType = requestMap.get("MsgType");
return MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType) && content.startsWith("快递");
}
@Override
public BaseMessage handleByMe(Map<String, String> requestMap) {
String expressQuery = requestMap.get("Content").trim();
String[] tokens = expressQuery.split("@");//快递@快递公司@单号
if (tokens.length!=3) {
return MessageFactory.createTextMessage(fromUserName, toUserName, ContentUtil.getExpressUsage());
}
return MessageFactory.createTextMessage(fromUserName, toUserName,
ExpressQueryService.getExpress(tokens[1], tokens[2]));
}
@Test
public void testHandleMessage(){
Map<String, String> requestMap = new HashMap<String, String>();
requestMap.put("FromUserName", "dfgsd");
requestMap.put("ToUserName", "dfsfd");
requestMap.put("MsgType", MessageUtil.REQ_MESSAGE_TYPE_TEXT);
requestMap.put("Content", "快递@"+"中通@"+"360387762616");
BaseMessage message = new ExpressQueryTextHandler().handleMessage(requestMap);
System.out.println(MessageUtil.messageToXml(message));
}
}
public static String getExpressUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("快递查询操作指南").append("\n\n");
buffer.append("回复:快递@快递公司@快递单号").append("\n");
buffer.append("回复“?/?”显示主菜单");
return buffer.toString();
}
/**
* 快递查询
* 爱快递http://www.aikuaidi.cn/rest/?key=ff4735a30a7a4e5a8637146fd0e7cec9&order={$keyword}&id=shentong&show=xml
* @author 熊诗言
*
*/
public class ExpressQueryService {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//配置申请的KEY
public static final String APPKEY ="2fcf423df0bff251751c02179187b7b4";
//1.快递查询API
@SuppressWarnings("unchecked")
public static String getExpress(String companyName,String expressNum){
String companyNum = getCompanyByName(companyName);
String result =null;
String url ="http://v.juhe.cn/exp/index";//请求接口地址
Map<String, Object> params = new HashMap<String, Object>();//请求参数
params.put("com",companyNum);//需要查询的快递公司编号
params.put("no",expressNum);//需要查询的订单号
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
params.put("dtype","json");//返回数据的格式,xml或json,默认json
StringBuffer buffer = new StringBuffer();
buffer.append("快递:"+companyName+"\n");
buffer.append("快递单号:"+expressNum+"\n");
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
object = object.getJSONObject("result");
JSONArray array = object.getJSONArray("list");
List<ExpressInfo> list = JSONArray.toList(array, new ExpressInfo() , new JsonConfig());
for (ExpressInfo expressInfo : list) {
buffer.append(expressInfo.getDatetime()).append(expressInfo.getRemark()).append("\n");
}
return buffer.toString();
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
}catch (Exception e) {
e.printStackTrace();
}
return "对不起,未查询到此快递";
}
/**
* [{"com":"顺丰","no":"sf"},{"com":"申通","no":"sto"},{"com":"圆通","no":"yt"},{"com":"韵达","no":"yd"},{"com":"天天","no":"tt"},{"com":"EMS","no":"ems"},{"com":"中通","no":"zto"},{"com":"汇通","no":"ht"},{"com":"全峰","no":"qf"}]
*/
//2.快递公司编号对照表
@SuppressWarnings("unchecked")
private static String getCompanyByName(String name){
String result =null;
String url ="http://v.juhe.cn/exp/com";//请求接口地址
Map<String, Object> params = new HashMap<String, Object>();//请求参数
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
List<CompanyPair> list = JSONArray.toList(object.getJSONArray("result"),
new CompanyPair(), new JsonConfig());
for (CompanyPair companyPair : list) {
if (companyPair.getCom().equals(name)) {
return companyPair.getNo();
}
}
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
private static String net(String strUrl, Map<String, Object> params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
strUrl = strUrl+"?"+urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try{
DataOutputStream out = new DataOutputStream(
conn.getOutputStream());
out.writeBytes(urlencode(params));
}catch (Exception e) {
// TODO: handle exception
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
//将map型转为请求参数型
public static String urlencode(Map<String, ?> data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, ?> i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static void main(String[] args) {
String info = getExpress("中通", "360387762616");
System.out.println(info);
}
}
public class CompanyPair{
private String com;
private String no;
。。。。
}
public class ExpressInfo {
private String datetime;
private String remark;
private String zone;
。。。。
}