• 使用Android显示疫情信息


    问题描述

      

     问题分析

      把数据通过服务器端发布,后由移动端接收数据并显示。

    源码

      python爬虫部分

      

     1 # author: pjh time: 2020/3/18
     2 # coding=utf-8
     3 import pymysql
     4 import requests
     5 import json
     6 
     7 url = "https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=316765403234"
     8 header = {"user-agent": "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 ("
     9                         "KHTML, like Gecko) Chrome/80.0.3987.116 Mobile Safari/537.36"}
    10 response = requests.get(url, headers=header)
    11 mydir = json.loads(response.content.decode())
    12 # 数据库的连接
    13 db = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='yiqing', charset='utf8')
    14 # 使用cursor方法创建一个游标
    15 cursor = db.cursor()
    16 for item in mydir['data']['areaTree']:
    17     name = item['name']
    18     confirm = item['total']['confirm']
    19     severe = item['total']['severe']
    20     heal = item['total']['heal']
    21     dead = item['total']['dead']
    22     suspect = item['total']['suspect']
    23     idcode = item['id']
    24     lastUpdateTime = item['lastUpdateTime']
    25     # 插入数据
    26     # sql = "insert into global(id,name,confirm,suspect,heal,dead,severe,idcode,lastupdatetime) values ({},'{}'," 
    27     #       "'{}','{}','{}','{}','{}','{}','{}');".format(
    28     #     0, name, confirm, suspect, heal, dead, severe, idcode, lastUpdateTime)
    29 
    30     # 更新数据
    31     sql = "update global set name='{}' confirm='{}',suspect='{}',heal='{}',dead='{}',severe='{}',lastupdatetime='{}'" 
    32           " where idcode='{}'".format(name, confirm, suspect, heal, dead, severe, lastUpdateTime, idcode)
    33     print(sql)
    34     cursor.execute(sql)
    35     db.commit()

      服务器端发布的servlet部分

      

     1 package com.pjh.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.annotation.WebServlet;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 import com.pjh.DBUtils.DBUtils;
    13 
    14 /**
    15  * Servlet implementation class sendDataServlet
    16  */
    17 @WebServlet("/sendDataServlet")
    18 public class sendDataServlet extends HttpServlet {
    19     private static final long serialVersionUID = 1L;
    20        
    21     /**
    22      * @see HttpServlet#HttpServlet()
    23      */
    24     public sendDataServlet() {
    25         super();
    26         // TODO Auto-generated constructor stub
    27     }
    28 
    29     /**
    30      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    31      */
    32     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    33         response.setContentType("text/html;charset=utf-8");
    34         request.setCharacterEncoding("utf-8");
    35         response.setCharacterEncoding("utf-8");
    36         PrintWriter out = response.getWriter();
    37         String date = request.getParameter("date");
    38         System.out.println(date);
    39         String result = DBUtils.queryGlobalLatestDataByDate2(date).toString();
    40         out.write(result);
    41         out.flush();
    42         out.close();
    43     }
    44 
    45     /**
    46      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    47      */
    48     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    49         // TODO Auto-generated method stub
    50         doGet(request, response);
    51     }
    52 
    53 }

      Android部分的代码

      在AndroidManifest.xml中添加两句代码用于联网:

    1 <uses-permission android:name="android.permission.INTERNET" />
    2 android:usesCleartextTraffic="true"

      activity_main.xml

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     android:orientation="vertical"
     6     android:id="@+id/activity_main"
     7     android:gravity="center_horizontal">
     8 
     9     <EditText
    10         android:id="@+id/query_date"
    11         android:layout_width="wrap_content"
    12         android:layout_height="wrap_content"
    13         android:ems="10"
    14         android:inputType="textPersonName"
    15         android:text=""/>
    16     <Button
    17         android:id="@+id/send_request"
    18         android:layout_width="wrap_content"
    19         android:layout_height="wrap_content"
    20         android:text="查询"/>
    21 
    22     <ListView
    23         android:layout_width="match_parent"
    24         android:layout_height="match_parent">
    25 
    26         <TextView
    27             android:id="@+id/response_data"
    28             android:layout_width="match_parent"
    29             android:layout_height="wrap_content"
    30             />
    31     </ListView>
    32 </LinearLayout>

      MainActivity.java

     1 package com.example.yiqing;
     2 
     3 import androidx.appcompat.app.AppCompatActivity;
     4 
     5 import android.os.Bundle;
     6 import android.view.View;
     7 import android.widget.Button;
     8 import android.widget.EditText;
     9 import android.widget.TextView;
    10 
    11 import java.io.BufferedReader;
    12 import java.io.IOException;
    13 import java.io.InputStream;
    14 import java.io.InputStreamReader;
    15 import java.net.HttpURLConnection;
    16 import java.net.MalformedURLException;
    17 import java.net.ProtocolException;
    18 import java.net.URL;
    19 
    20 public class MainActivity extends AppCompatActivity {
    21 
    22     private TextView textView;
    23     @Override
    24     protected void onCreate(Bundle savedInstanceState) {
    25         super.onCreate(savedInstanceState);
    26         setContentView(R.layout.activity_main);
    27         findViewById(R.id.send_request).setOnClickListener(new View.OnClickListener() {
    28             @Override
    29             public void onClick(View v) {
    30                 sendData();
    31             }
    32         });
    33 
    34         textView = (TextView) findViewById(R.id.response_data);
    35     }
    36 
    37     private void sendData() {
    38         //开启线程,发送请求
    39         new Thread(new Runnable() {
    40             @Override
    41             public void run() {
    42                 HttpURLConnection connection = null;
    43                 BufferedReader reader = null;
    44                 try {
    45 //                    EditText editText = findViewById(R.id.query_date);
    46 //                    String date = editText.getText().toString();
    47                     URL url = new URL("http://10.0.2.2:8086/yiqing/sendDataServlet?date=2020-03-18");
    48 //                    URL url = new URL("http://www.163.com");
    49                     connection = (HttpURLConnection) url.openConnection();
    50                     //设置请求方法
    51                     connection.setRequestMethod("GET");
    52                     //设置连接超时时间(毫秒)
    53                     connection.setConnectTimeout(5000);
    54                     //设置读取超时时间(毫秒)
    55                     connection.setReadTimeout(5000);
    56 
    57                     //返回输入流
    58                     InputStream in = connection.getInputStream();
    59 
    60                     //读取输入流
    61                     reader = new BufferedReader(new InputStreamReader(in));
    62                     StringBuilder result = new StringBuilder();
    63                     String line;
    64                     while ((line = reader.readLine()) != null) {
    65                         result.append(line);
    66                     }
    67                     show(result.toString());
    68                 } catch (MalformedURLException e) {
    69                     e.printStackTrace();
    70                 } catch (ProtocolException e) {
    71                     e.printStackTrace();
    72                 } catch (IOException e) {
    73                     e.printStackTrace();
    74                 } finally {
    75                     if (reader != null) {
    76                         try {
    77                             reader.close();
    78                         } catch (IOException e) {
    79                             e.printStackTrace();
    80                         }
    81                     }
    82                     if (connection != null) {//关闭连接
    83                         connection.disconnect();
    84                     }
    85                 }
    86             }
    87         }).start();
    88 
    89     }
    90 
    91     private void show(final String result) {
    92         runOnUiThread(new Runnable() {
    93             @Override
    94             public void run() {
    95                     textView.setText(result);
    96             }
    97         });
    98     }
    99 }
  • 相关阅读:
    声明了变量并赋了初始值,但在VS中报当前上下文中不存在名称“ XXX”的错误 Kevin
    delphi中的nil值 Kevin
    MVC3 + Ajax 图片上传总结 Kevin
    EntityFramework 更新数据库的问题 Kevin
    MVC3 EntityFramework 插入Mysql数据库 乱码问题 Kevin
    MVC Html 编码问题 Kevin
    周鸿祎:共享软件无合理商业模式才变流氓
    C++界面库 Xtreme Toolkit Pro[转载]
    《创业10个小诀窍》
    软件商业模式分析之-迅雷
  • 原文地址:https://www.cnblogs.com/52bb/p/12552527.html
Copyright © 2020-2023  润新知