1. 程式人生 > 程式設計 >Android開發疫情查詢app

Android開發疫情查詢app

一丶工作原理:

App 通過請求本地tomcat釋出的servlet (呼叫了 HttpURLConnection 方法)獲取MySQL資料庫當中的資料,獲取資料並返回到App 當中,顯示給使用者。(其中傳遞的格式為 json)

使用的工具:Android Studio 開發APP Eclipse 釋出Servlet,資料傳遞

二丶執行程式碼:

Tomcat 釋出的Servlet 類:

package com.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Bean.worldbean;
import com.Dao.Dao;
import com.google.gson.Gson;



/**
 * Servlet implementation class Worldservlet
 */
@WebServlet("/Worldservlet")
public class Worldservlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public Worldservlet() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    String s=null;
    //獲取傳遞過來的引數
    String date = request.getParameter("date");
    String name =request.getParameter("name");
    // Gson 谷歌推出的用於生成和解析JSON 資料格式的工具 使用時需要 匯入jar 包 我的是 gson-2.6.2.jar
    Gson gson=new Gson();
    try {
      worldbean info= Dao.getinfo(date,name);
      //將資料 轉換為 Json 格式
      s=gson.toJson(info);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //System.out.println(s);
    //方法作用 只能列印輸出文字格式的(包括html標籤) 不可列印物件
    response.getWriter().write(s);

  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request,IOException {
    // TODO Auto-generated method stub
    doGet(request,response);
  }

}

As 當中的MainActivity:

package com.example.yiqingdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
  EditText editTextCountry,editTextDate;
  TextView textView;
  Button button;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editTextCountry = findViewById(R.id.editText4);
    editTextDate = findViewById(R.id.editText3);
    textView = findViewById(R.id.textView2);
    button = findViewById(R.id.button);
    button.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            //本機tomcat 釋出的網站 其實是一個servlet 類 必須先讓本機發布(啟動tomcat 執行) 然後才能訪問改網站
            String url = "http://192.168.0.106:8080/YiQingSearch/Worldservlet?date=" + editTextDate.getText().toString() + "&name=" + editTextCountry.getText().toString();
            get(url);
          }
        }
    );
  }

  public void get(final String url) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        HttpURLConnection connection = null;
        InputStream is = null;


        try {
          //獲取url 物件
          URL Url = new URL(url);
          //獲取httpURlConnection 物件
          connection = (HttpURLConnection) Url.openConnection();
          //預設為get方法 or post
          connection.setRequestMethod("GET");
          //預設不使用快取
          connection.setUseCaches(false);
          //設定連線超時時間 單位毫秒
          connection.setConnectTimeout(10000);
          //設定讀取超時時間
          connection.setReadTimeout(10000);
          //設定是否從httpUrlConnection 讀入,預設為true
          connection.setDoInput(true);

          //相應的碼數為 200
          if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            //獲取輸入流
            is = connection.getInputStream();
            //將輸入流內的資料變為Sting型別資料
            String info = getStringFromInputStream(is);
            //轉換為JSON 型別便於讀取
            JSONObject jsonObject = new JSONObject(info);
            textView.setText(
                "更新時間:" + jsonObject.getString("updatetime") +
                    "\n確診人數:" + jsonObject.getString("confirm")
                    + "\n死亡人數:" + jsonObject.getString("dead")
                    + "\n治癒人數:" + jsonObject.getString("heal")
            );


            /* //獲取url 網頁的原始碼
            BufferedReader reader= new BufferedReader(new InputStreamReader(is));  //包裝位元組流為字元流
            StringBuilder response = new StringBuilder();
            String line;


            while((line = reader.readLine())!=null){

              response.append(line);
            }

            String s = response.toString();
            */
          }
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (connection != null) {
            connection.disconnect();
          }
        }

      }
    }).start();

  }

  private static String getStringFromInputStream(InputStream is) throws Exception {
    //定義位元組陣列快取區
    ByteArrayOutputStream by = new ByteArrayOutputStream();
    byte[] buff = new byte[1024];
    int len = -1;
    while ((len = is.read(buff)) != -1) {
      by.write(buff,len);
    }
    is.close();
    //將緩衝區的資料轉換為 String 型別
    String html = by.toString();
    by.close();
    return html;
  }

}

除此之外還需要給APP賦予許可權 :

As 的 AndroidMainfest 如下:

添加註釋的為自主新增的許可權

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.yiqingdemo">

  <uses-permission android:name="android.permission.INTERNET" /> <!--聯網所需要的許可權-->
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 主要用於管理 WIFI 連線的各方面-->
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!--主要用於監視一般網路連線 -->

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">   <!-- 指示應用程式是否打算使用明文網路流量  -->
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>

</manifest>

三丶 執行結果:

Android開發疫情查詢app

以上就是Android開發例項(疫情查詢app)的詳細內容,更多關於Android開發APP的資料請關注我們其它相關文章!