时间:2021-09-11 08:10:15 | 栏目:Android代码 | 点击:次
一丶工作原理:
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, 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 发布的网站 其实是一个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, 0, 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>
三丶 运行结果: