Android開發(fā)疫情查詢app(實例代碼)
一丶工作原理:
App 通過請求本地tomcat發(fā)布的servlet (調(diào)用了 HttpURLConnection 方法)獲取MySQL數(shù)據(jù)庫當中的數(shù)據(jù),獲取數(shù)據(jù)并返回到App 當中,顯示給用戶。(其中傳遞的格式為 json)
使用的工具:Android Studio 開發(fā)APP Eclipse 發(fā)布Servlet,數(shù)據(jù)傳遞
二丶運行代碼:
Tomcat 發(fā)布的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; //獲取傳遞過來的參數(shù) String date = request.getParameter('date'); String name =request.getParameter('name'); // Gson 谷歌推出的用于生成和解析JSON 數(shù)據(jù)格式的工具 使用時需要 導入jar 包 我的是 gson-2.6.2.jar Gson gson=new Gson(); try { worldbean info= Dao.getinfo(date,name); //將數(shù)據(jù) 轉(zhuǎn)換為 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, HttpServletResponse response) throws ServletException, 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 發(fā)布的網(wǎng)站 其實是一個servlet 類 必須先讓本機發(fā)布(啟動tomcat 運行) 然后才能訪問改網(wǎng)站 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); //設(shè)置連接超時時間 單位毫秒 connection.setConnectTimeout(10000); //設(shè)置讀取超時時間 connection.setReadTimeout(10000); //設(shè)置是否從httpUrlConnection 讀入,默認為true connection.setDoInput(true); //相應的碼數(shù)為 200 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { //獲取輸入流 is = connection.getInputStream(); //將輸入流內(nèi)的數(shù)據(jù)變?yōu)镾ting類型數(shù)據(jù) String info = getStringFromInputStream(is); //轉(zhuǎn)換為JSON 類型便于讀取 JSONObject jsonObject = new JSONObject(info); textView.setText( '更新時間:' + jsonObject.getString('updatetime') + 'n確診人數(shù):' + jsonObject.getString('confirm') + 'n死亡人數(shù):' + jsonObject.getString('dead') + 'n治愈人數(shù):' + jsonObject.getString('heal') ); /* //獲取url 網(wǎng)頁的源代碼 BufferedReader reader= new BufferedReader(new InputStreamReader(is)); //包裝字節(jié)流為字符流 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 { //定義字節(jié)數(shù)組緩存區(qū) ByteArrayOutputStream by = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len = -1; while ((len = is.read(buff)) != -1) { by.write(buff, 0, len); } is.close(); //將緩沖區(qū)的數(shù)據(jù)轉(zhuǎn)換為 String 類型 String html = by.toString(); by.close(); return html; }}
除此之外還需要給APP賦予權(quán)限 :
As 的 AndroidMainfest 如下:
添加注釋的為自主添加的權(quán)限
<?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' /> <!--聯(lián)網(wǎng)所需要的權(quán)限--> <uses-permission android:name='android.permission.ACCESS_WIFI_STATE' /> <!-- 主要用于管理 WIFI 連接的各方面--> <uses-permission android:name='android.permission.ACCESS_NETWORK_STATE' /> <!--主要用于監(jiān)視一般網(wǎng)路連接 --> <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'> <!-- 指示應用程序是否打算使用明文網(wǎng)絡流量 --> <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>
三丶 運行結(jié)果:
以上就是Android開發(fā)實例(疫情查詢app)的詳細內(nèi)容,更多關(guān)于Android開發(fā)APP的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程3. CSS3中Transition屬性詳解以及示例分享4. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享5. ASP常用日期格式化函數(shù) FormatDate()6. asp.net core項目授權(quán)流程詳解7. js select支持手動輸入功能實現(xiàn)代碼8. vue使用moment如何將時間戳轉(zhuǎn)為標準日期時間格式9. 開發(fā)效率翻倍的Web API使用技巧10. jsp文件下載功能實現(xiàn)代碼
