一丶工作原理:
App 通过请求本地tomcat发布的servlet (调用了 HttpURLConnection 方法)获取MySQL数据库当中的数据,获取数据并返回到App 当中,显示给用户。(其中传递的格式为 json)
使用的工具:Android Studio 开发APP Eclipse 发布Servlet,数据传递
二丶运行代码:
Tomcat 发布的Servlet 类:
1 package com.Servlet; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import com.Bean.worldbean; 11 import com.Dao.Dao; 12 import com.google.gson.Gson; 13 14 15 16 /** 17 * Servlet implementation class Worldservlet 18 */ 19 @WebServlet("/Worldservlet") 20 public class Worldservlet extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public Worldservlet() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 /** 32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 // TODO Auto-generated method stub 36 response.setContentType("text/html;charset=UTF-8"); 37 request.setCharacterEncoding("UTF-8"); 38 String s=null; 39 //获取传递过来的参数 40 String date = request.getParameter("date"); 41 String name =request.getParameter("name"); 42 // Gson 谷歌推出的用于生成和解析JSON 数据格式的工具 使用时需要 导入jar 包 我的是 gson-2.6.2.jar 43 Gson gson=new Gson(); 44 try { 45 worldbean info= Dao.getinfo(date,name); 46 //将数据 转换为 Json 格式 47 s=gson.toJson(info); 48 } catch (Exception e) { 49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 } 52 //System.out.println(s); 53 //方法作用 只能打印输出文本格式的(包括html标签) 不可打印对象 54 response.getWriter().write(s); 55 56 } 57 58 /** 59 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 60 */ 61 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 62 // TODO Auto-generated method stub 63 doGet(request, response); 64 } 65 66 }
As 当中的MainActivity:
1 package com.example.yiqingdemo; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.os.Bundle; 6 import android.util.Log; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.EditText; 10 import android.widget.TextView; 11 12 import org.json.JSONObject; 13 14 import java.io.BufferedInputStream; 15 import java.io.BufferedReader; 16 import java.io.ByteArrayOutputStream; 17 import java.io.IOException; 18 import java.io.InputStream; 19 import java.io.InputStreamReader; 20 import java.net.HttpURLConnection; 21 import java.net.MalformedURLException; 22 import java.net.URL; 23 24 public class MainActivity extends AppCompatActivity { 25 EditText editTextCountry, editTextDate; 26 TextView textView; 27 Button button; 28 29 @Override 30 protected void onCreate(Bundle savedInstanceState) { 31 super.onCreate(savedInstanceState); 32 setContentView(R.layout.activity_main); 33 editTextCountry = findViewById(R.id.editText4); 34 editTextDate = findViewById(R.id.editText3); 35 textView = findViewById(R.id.textView2); 36 button = findViewById(R.id.button); 37 button.setOnClickListener( 38 new View.OnClickListener() { 39 @Override 40 public void onClick(View v) { 41 //本机tomcat 发布的网站 其实是一个servlet 类 必须先让本机发布(启动tomcat 运行) 然后才能访问改网站 42 String url = "http://192.168.0.106:8080/YiQingSearch/Worldservlet?date=" + editTextDate.getText().toString() + "&name=" + editTextCountry.getText().toString(); 43 get(url); 44 } 45 } 46 ); 47 } 48 49 public void get(final String url) { 50 new Thread(new Runnable() { 51 @Override 52 public void run() { 53 HttpURLConnection connection = null; 54 InputStream is = null; 55 56 57 try { 58 //获取url 对象 59 URL Url = new URL(url); 60 //获取httpURlConnection 对象 61 connection = (HttpURLConnection) Url.openConnection(); 62 //默认为get方法 or post 63 connection.setRequestMethod("GET"); 64 //默认不使用缓存 65 connection.setUseCaches(false); 66 //设置连接超时时间 单位毫秒 67 connection.setConnectTimeout(10000); 68 //设置读取超时时间 69 connection.setReadTimeout(10000); 70 //设置是否从httpUrlConnection 读入,默认为true 71 connection.setDoInput(true); 72 73 //相应的码数为 200 74 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 75 //获取输入流 76 is = connection.getInputStream(); 77 //将输入流内的数据变为Sting类型数据 78 String info = getStringFromInputStream(is); 79 //转换为JSON 类型便于读取 80 JSONObject jsonObject = new JSONObject(info); 81 textView.setText( 82 "更新时间:" + jsonObject.getString("updatetime") + 83 " 确诊人数:" + jsonObject.getString("confirm") 84 + " 死亡人数:" + jsonObject.getString("dead") 85 + " 治愈人数:" + jsonObject.getString("heal") 86 ); 87 88 89 /* //获取url 网页的源代码 90 BufferedReader reader= new BufferedReader(new InputStreamReader(is)); //包装字节流为字符流 91 StringBuilder response = new StringBuilder(); 92 String line; 93 94 95 while((line = reader.readLine())!=null){ 96 97 response.append(line); 98 } 99 100 String s = response.toString(); 101 */ 102 } 103 } catch (Exception e) { 104 e.printStackTrace(); 105 } finally { 106 if (connection != null) { 107 connection.disconnect(); 108 } 109 } 110 111 } 112 }).start(); 113 114 } 115 116 private static String getStringFromInputStream(InputStream is) throws Exception { 117 //定义字节数组缓存区 118 ByteArrayOutputStream by = new ByteArrayOutputStream(); 119 byte[] buff = new byte[1024]; 120 int len = -1; 121 while ((len = is.read(buff)) != -1) { 122 by.write(buff, 0, len); 123 } 124 is.close(); 125 //将缓冲区的数据转换为 String 类型 126 String html = by.toString(); 127 by.close(); 128 return html; 129 } 130 131 }
除此之外还需要给APP赋予权限 :
As 的 AndroidMainfest 如下:
添加注释的为自主添加的权限
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.yiqingdemo"> 4 5 <uses-permission android:name="android.permission.INTERNET" /> <!--联网所需要的权限--> 6 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 主要用于管理 WIFI 连接的各方面--> 7 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!--主要用于监视一般网路连接 --> 8 9 <application 10 android:allowBackup="true" 11 android:icon="@mipmap/ic_launcher" 12 android:label="@string/app_name" 13 android:roundIcon="@mipmap/ic_launcher_round" 14 android:supportsRtl="true" 15 android:theme="@style/AppTheme" 16 android:usesCleartextTraffic="true"> <!-- 指示应用程序是否打算使用明文网络流量 --> 17 <activity android:name=".MainActivity"> 18 <intent-filter> 19 <action android:name="android.intent.action.MAIN" /> 20 21 <category android:name="android.intent.category.LAUNCHER" /> 22 </intent-filter> 23 </activity> 24 </application> 25 26 </manifest>
三丶 运行结果: