从网页获取数据

1. 辛老师教程

1.1. 需要的文件、资源

1、视频教程:获取航班、伴车星及船舶的GPS数据

2、需要的代码文件:Java后台Servlet自动循环获取伴车星数据参考

  1. 需要获取数据的界面(需要插入链接):
  1. 参考代码:

1.2. 步骤(后面来写)

2. 代码

2.1. 前端代码

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
  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>
  <base href="<%=basePath%>">

  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
</head>

<body>
This is my JSP page. <br>
</body>
</html>

2.2. 后端代码

1、GetNetworkData.java

package gps.data;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

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

import org.json.JSONException;
import org.json.JSONObject;

public class GetNetworkData implements ServletContextListener {
    private Timer timer = null;
    private TimerTask task=null;
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("================>[ServletContextListener]自动加载启动开始.");
        timer = new Timer(true);
        java.util.Date date = (new Date());
        MyTimerTask task = new MyTimerTask();
        timer.schedule(task, 2000,20000);		//延迟2秒后,每隔20秒运行一次
        System.out.println("[GetNetworkData]运行了");
    }
    public class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("Current Time:"+format.format(calendar.getTime()));//获取当前系统时间
            try {//多用函数
                loginGPS();
                getGPSData();
            } catch (MalformedURLException | JSONException | SQLException e) {
                e.printStackTrace();
            }
        }
    }
    boolean login=false;
    String urlData="http://www.bcxgps.com/page/vip/showTerminalG.action?vip_id=0&currentPage=1&type=0&pageCount=60&search=&startType=0&line=on";
    String urlLogin="http://www.bcxgps.com/page/login/BcxLoad.action?r=g";

    public void loginGPS() throws MalformedURLException, JSONException, SQLException {
        if(!login){
            CookieManager manager = new CookieManager();
            CookieHandler.setDefault(manager);
            URL urlConn=new URL(urlLogin);
            getUrl(urlConn);
            login=true;
            System.out.println("登录网站");
        }
    }

    public void getGPSData() throws MalformedURLException, JSONException, SQLException {//多用throw
        URL urlConn=new URL(urlData);
        getUrl(urlConn);
        System.out.println("获取数据");
    }
    private void getUrl(URL urlConn) throws JSONException, SQLException {
        try {
            //创建连接
            HttpURLConnection connection = (HttpURLConnection) urlConn.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            DataOutputStream out = new
                    DataOutputStream(connection.getOutputStream());
            JSONObject obj = new JSONObject();
            String json = java.net.URLEncoder.encode(obj.toString(), "utf-8");	//这里传递参数
            out.writeBytes(json);
            out.flush();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(connection.getInputStream(),"UTF-8"));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
            System.out.println(sb);

            GPSDao dao=new GPSDao();
            dao.addGPSRecord(sb);

            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、GPSDao

package gps.data;
//多用函数分开
//每个函数入口检查参数是否正确
//循序渐渐,一步步来,做一步,运行检验一步
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GPSDao {
    Statement statement=null;
    public void addGPSRecord(StringBuffer sb) throws JSONException, SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException classnotfoundexception) {
            classnotfoundexception.printStackTrace();
        }
        System.out.println("加载了JDBC驱动");
        Connection conn = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/test?user=root&password=955240&useUnicode=true&characterEncoding=UTF-8");
        System.out.println("准备statement。");
        statement = conn.createStatement();
        System.out.println("已经链接上数据库!");
        System.out.println("Connect Database Ok!!!<br>");
        
        //字符串转换成json并解析出来
        String result=sb.toString();
        if(!result.isEmpty()){
            JSONObject json=new JSONObject(result);
            JSONArray array=(JSONArray) json.get("list");
            for(int i=0;i<array.length();i++){
                JSONObject record=(JSONObject) array.get(i);
                addGPSRecord(record);
            }
        }
        statement.close();
        conn.close();
        System.out.println("Database Closed!!!<br>");
        System.out.println("操作数据完毕,关闭了数据库!");
    }

    private void addGPSRecord(JSONObject record) throws JSONException {
        String deviceId="XXXXXXXXX";
        String longitude="104.02";
        String latitude="30.34";
        String address="某某某地方";
        String gpsTime="2020-10-14 22:54:00";
        String creatorId="200000000000000";
        String creator="某某某";
        String createTime="2020-10-14 22:58:00";

        deviceId=record.getString("sn");
        longitude=record.getString("lon");
        latitude=record.getString("lat");
        address=record.getString("address");
        gpsTime=record.getString("gpstime");
        
        //然后链接数据库,开始操作数据表
        try {
            String sql = "insert into gps_data(device_id,longitude,latitude,address,gps_time,creator_id,creator,create_time) values('"
                    + deviceId + "'," + longitude + ","+latitude+",'"+address+"','"+gpsTime+"','"+creatorId+"','"+creator+"','"+createTime+"')";
            System.out.println("即将执行的SQL语句是:"+sql);
            statement.executeUpdate(sql);
        } catch (SQLException sqlexception) {
            sqlexception.printStackTrace();
        }
    }

}

2.3. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>GetNetworkData</display-name>
    <servlet>
        <servlet-name>GetNetworkData</servlet-name>
        <display-name>This is the display name of my J2EE component</display-name>
        <description>This is the description of my J2EE component</description>
        <servlet-class>gps.data.GetNetworkData</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>GetNetworkData</servlet-name>
        <url-pattern>/servlet/GetNetworkData</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <listener>
        <listener-class>gps.data.GetNetworkData</listener-class>
    </listener>
</web-app>

3. 框架

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值