A Dian works:
App request by the local tomcat servlet released (called HttpURLConnection acquisition method) data out of MySQL database, get data and returns to the App which is displayed to the user. (Wherein the transfer format is json)
Use tools: Android Studio developers APP Eclipse release Servlet, data transfer
Two Dian run the code:
Tomcat Servlet class released:
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 DATE request.getParameter = String ( "DATE" ); 41 is String name = request.getParameter ( "name" ); 42 is // Gson Google Release for generating and parsing packets need to import jar me JSON data format used tools is-2.6.2.jar GSON 43 is Gson GSON = new new Gson (); 44 is the try { 45 worldbean info = Dao.getinfo (DATE, name); 46 is // converts the data format into Json 47 S = gson.toJson (info ); 48 } the catch (Exception E) { 49 // the TODO Auto-Generated Block the catch 50 e.printStackTrace (); 51 is } 52 is // System.out.println (S); 53 is // method can effect the printout of the text (including html tags) can not be printed 54 is response.getWriter () Write (S. ); 55 56 is } 57 is 58 / ** 59 * @see the HttpServlet # the doPost (the HttpServletRequest Request, the HttpServletResponse Response) 60 * / 61 is protected void the doPost (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { 62 is // the TODO Auto-Generated Stub Method, 63 doGet(request, response); 64 } 65 66 }
As among 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 newView.OnClickListener () { 39 @Override 40 public void onClick (View v) { 41 // native tomcat published on the website is actually a servlet class must be published (start tomcat run) let the machine before you can access the Web site to change 42 String = URL "http://192.168.0.106:8080/YiQingSearch/Worldservlet?date=" + editTextDate.getText () toString () + "& name =" +. editTextCountry.getText () toString ();. 43 is GET (URL ); 44 is } 45 } 46 is ); 47 } 48 49 public void GET ( FinalUrl String) { 50 new new the Thread ( new new the Runnable () { 51 is @Override 52 is public void RUN () { 53 is the HttpURLConnection Connection = null ; 54 is the InputStream IS = null ; 55 56 is 57 is the try { 58 // Get the object url 59 the URL the Url = new new the URL (URL); 60 // Get httpURlConnection the object 61 is Connection =(The HttpURLConnection) url.openConnection (); 62 is // defaults to get POST method or 63 is connection.setRequestMethod ( "the GET" ); 64 // default no cache 65 connection.setUseCaches ( to false ); 66 // set connection time milliseconds 67 connection.setConnectTimeout (10000 ); 68 // set the read timeout 69 connection.setReadTimeout (10000 ); 70 // settings are read from httpUrlConnection, defaults to true 71 is connection.setDoInput ( to true); 72 73 is // corresponding code number 200 is 74 IF (connection.getResponseCode () == HttpURLConnection.HTTP_OK) { 75 // Get the input stream 76 IS = connection.getInputStream (); 77 // input stream within Sting data becomes data type 78 String info = getStringFromInputStream (iS); 79 // convert JSON type easy to read 80 the jSONObject jsonObject = new new the jSONObject (info); 81 textView.setText ( 82 "Updated:" + jsonObject.getString ( "updatetime") + 83 "\ the n-number of people diagnosed:" + jsonObject.getString ( "Confirm The" ) 84 + "\ the n-number of deaths:" + jsonObject.getString ( "Dead" ) 85 + "\ n-cure number:" + jsonObject.getString ( "heal" ) 86 ); 87 88 89 / * // url acquired page source 90 the BufferedReader Reader the BufferedReader new new = (the InputStreamReader new new (iS)); // packed byte character stream stream 91 is the StringBuilder the StringBuilder new new Response = (); 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-1 = len ; 121 the while ((len = is.read (BUFF)) = -1! ) { 122 by.write (BUFF, 0 , len); 123 } 124 is.close (); 125 // buffer the data conversion section is of type String 126 String HTML = by.toString (); 127 by.close (); 128 return HTML; 129 } 130. 131 is }
In addition also you need to give permission to the APP:
As the AndroidMainfest follows:
Add a comment to add their own authority
. 1 <? XML Version = "1.0" encoding = "UTF-. 8" ?> 2 < the manifest xmlns: Android = "http://schemas.android.com/apk/res/android" . 3 Package = "the com.example. yiqingdemo " > . 4 . 5 < uses-permission Android: name =" android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE " /> ! <- permissions required network -> . 6 < uses-permission Android: name =" android.permission.ACCESS_WIFI_STATE " /> <! - mainly used for management of all aspects of the WIFI connection -> 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"> <!- -> Indicates whether the application intends to use the simple network traffic 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>
Wed and operating results: