您的位置:首页 > 理论基础 > 计算机网络

【HttpClient学习与实战】2.使用httpclient实现快递查询网站

2016-07-06 15:43 501 查看
上一次我们自己编写了一个数据接口,并且使用httpClient进行了get和post对http信息进行了请求和获取回复。

我们这次去真正的访问一个第三方数据接口,来开发一个实际的应用。

我们要完成的是一个快递查询的网站,淘了很久,发现了一个比较权威且有用的快递物流数据接口:

获取json格式的物流快递信息 http://www.kuaidi100.com/query?type=快递公司代号&postid=快递单号
ps:快递公司编码:申通="shentong" EMS="ems" 顺丰="shunfeng" 圆通="yuantong" 中通="zhongtong" 韵达="yunda" 天天="tiantian" 汇通="huitongkuaidi" 全峰="quanfengkuaidi" 德邦="debangwuliu" 宅急送="zhaijisong"

效果:



接下来我们就在上次我们创建的httpTest工程(一个WebProject)里面创建我们的应用。

首先我们编写快递查询的首页,一个jsp页面,我们就拿httpTest工程中默认的index.jsp写:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>程序猿快递查询网</title>

</head>

<body style="color: #FFFFFF;background-color: #000000">
<center><h1>程序猿快递查询网</h1>
<form method="post" action="<%=basePath %>KuaiDiQuery">
要查询的快递公司:<br/>
<input type="text" name="type"><br/>
要查询的快递单号:<br/>
<input type="text" name="postid"><br/>
<input type="submit" value="查询">
</form>
</center>
</body>
</html>
页面效果:



然后创建相应的Servlet进行处理:





然后查看Web.xml中是否注册该Servlet:



要注意的是,该Servlet中就要做到使用httpClient去请求快递查询的数据接口,然后进行数据解析(解析json这一块这里不再赘述,想要学习的同学可以专门去搜索相关资源学习),最终将快递信息呈现在页面上。

下面是该Servlet的具体实现,我们这里使用的是post请求:
package kuaidi;

import httpcall.HttpClientUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;

public class KuaiDiQuery extends HttpServlet {
private static final Log log=LogFactory.getLog(HttpClientUtil.class);

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-type", "text/html;charset=UTF-8");

PrintWriter out=response.getWriter();
String code=request.getParameter("type");
String postid=request.getParameter("postid");

String type="";
if(code.contains("申通")){
type="shentong";
}else if(code.contains("EMS")){
type="ems";
}else if(code.contains("顺丰")){
type="shunfeng";
}else if(code.contains("圆通")){
type="yuantong";
}else if(code.contains("中通")){
type="zhongtong";
}else if(code.contains("韵达")){
type="yunda";
}else if(code.contains("天天")){
type="tiantian";
}else if(code.contains("汇通")){
type="huitongkuaidi";
}else if(code.contains("全峰")){
type="quanfengkuaidi";
}else if(code.contains("德邦")){
type="debangwuliu";
}else if(code.contains("宅急送")){
type="zhaijisong";
}else{
type="null";
}

if(!type.equals("null")&&!type.equals("")&&postid!=null&&!postid.equals("")){
out.println("<html><head><title>查询结果</title><head>" +
"<body style=\"color: #FFFFFF;background-color: #000000\">" +
"<center>您查询的是<font color='red'><b>"+code+"</b></font>的快递<br/>");
String jsonText=postHttp(type,postid);

//解析json,获取有用数据
try {
JSONObject jsonObject=new JSONObject(jsonText);
//array.getJSONObject(0);
String ischeck=jsonObject.getString("ischeck");
String updatetime=jsonObject.getString("updatetime");
String codenumber=jsonObject.getString("codenumber");
out.print("<h2>快递订单信息</h2><table border=\"1\" cellspacing=\"0\" cellpadding=\"0\"><tr>"+
"<th>快递单号</th><th>是否签收</th><th>更新时间</th>"+
"</tr><tr>"+
"<td>"+codenumber+"</td>"+
"<td>"+(ischeck.equals("1")?"已签收":"未签收")+"</td>"+
"<td>"+updatetime+"</td>"+
"</tr></table><br/>");

out.print("<h2>快递运送信息</h2><table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">" +
"<tr><th>状态</th><th>时间</th></tr>");
JSONArray dataList=jsonObject.getJSONArray("data");
for (int j = 0; j < dataList.length(); j++) {
JSONObject dataObject=dataList.getJSONObject(j);
String context=dataObject.getString("context");
String ftime=dataObject.getString("ftime");
out.print("<tr><td>"+context+"</td>"+
"<td>"+ftime+"</td>"+
"</tr>");
}
out.print("</table></center></body></html>");
} catch (Exception e) {
e.printStackTrace();
}

}else{
out.print("<font color='red'><b>快递公司名称或订单号不存在!请查证后再次查询</b></font>");
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}

/**
* post 方式
* @param type
* @param postid
* @return String
* */
public static String postHttp(String type,String postid){
String responseMsg="";

//1.构造HttpClient的实例
HttpClient httpClient=new HttpClient();

httpClient.getParams().setContentCharset("utf-8");

String url="http://www.kuaidi100.com/query";

//2.构造PostMethodd的实例
PostMethod postMethod=new PostMethod(url);

//3.把参数值放入到PostMethod对象中
postMethod.addParameter("type",type);
postMethod.addParameter("postid",postid);

try {
//4.执行postMethod,调用http接口
httpClient.executeMethod(postMethod);//200

//5.读取内容
responseMsg = postMethod.getResponseBodyAsString();

//6.处理返回的内容
log.info(responseMsg);
} catch (Exception e) {
e.printStackTrace();
}finally{
//7.释放连接
postMethod.releaseConnection();
}
return responseMsg;
}
}
运行我们的项目,搜索韵达的一个单子(之前自己买桌子时的订单),结果:





至此,我们利用httpClient获取了网络上的第三方数据接口来完成了一个快递查询服务。目前比较火爆的移动互联网中,愈来愈多的微信公众号、微网站和手机App,都采用了第三方数据接口来提供一些常见的数据服务,例如天气查询、手机归属地查询、每日笑话、股票走势等等......学会合理利用网络资源,就会使开发的应用功能更丰富,吸引更多的用户。

彩蛋:

一个包含许多免费数据服务接口的地址集合(天气预报、手机归属地等等...):
http://www.bejson.com/knownjson/webInterface/
转载请注明出处:http://blog.csdn.net/acmman/article/details/51839525
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: