Android端通过http访问web端servlet获取数据

  关于wjm的这次作业,当我发现我必须要写APP的时候,我的心是拔凉拔凉的。我疯狂地查资料查博客,本想通过开通mysql远程连接,andriod直接通过pc的ip地址访问mysql,也就是android直连mysql。无奈android开发平台是基于Android Studio的,其不可导入mysqk的jdbc.jar包,出现如Android Studio已有sql资源包,不可再导入此类jar包的错误。查找了半天也没找出解决的办法。讲道理我假期还是有认真学过一点Android,但是这个确实是搞了半天都没能实现啊。

  好在这时候发现可以通过一种基于servlet为服务器的中转实现方式,其主要的思路为:通过servlet搭建的服务器将mysql中需要的数据取出来发布在以tomcat为支持的网页上,android端直接访问该网页,将网页中的数据全部取出。然后第二天就停了一天的电,晚上7点才来电,好在2小时左右就解决了。下面直接上代码,有问题请自行查阅相关资料或在博客下方留言(我看到了会回复的)。

Android端MainActivity

  1 package com.example.baiducs;
  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 java.io.BufferedInputStream;
 13 import java.io.BufferedReader;
 14 import java.io.IOException;
 15 import java.io.InputStream;
 16 import java.io.InputStreamReader;
 17 import java.io.Reader;
 18 import java.net.HttpURLConnection;
 19 import java.net.MalformedURLException;
 20 import java.net.ProtocolException;
 21 import java.net.URL;
 22 
 23 public class MainActivity extends AppCompatActivity {
 24     private TextView textView;
 25     @Override
 26     protected void onCreate(Bundle savedInstanceState) {
 27         super.onCreate(savedInstanceState);
 28         setContentView(R.layout.activity_main);
 29         findViewById(R.id.send_request).setOnClickListener(new View.OnClickListener() {
 30             @Override
 31             public void onClick(View v) {
 32                 send();
 33             }
 34         });
 35 
 36         textView = (TextView) findViewById(R.id.response_data);
 37     }
 38 
 39     private void send() {
 40         //开启线程,发送请求
 41         new Thread(new Runnable() {
 42             @Override
 43             public void run() {
 44                 HttpURLConnection connection = null;
 45                 BufferedReader reader = null;
 46                 try {
 47                     EditText editText =(EditText)findViewById(R.id.editText);
 48                     String timeend = editText.getText().toString();
 49                     URL url = new URL("http://10.0.2.2:8080/ydyq/dengluServlet?timeend="+timeend);
 50                     //URL url = new URL("https://www.baidu.com/");
 51                     connection = (HttpURLConnection) url.openConnection();
 52                     //设置请求方法
 53                     connection.setRequestMethod("GET");
 54                     //设置连接超时时间(毫秒)
 55                     connection.setConnectTimeout(5000);
 56                     //设置读取超时时间(毫秒)
 57                     connection.setReadTimeout(5000);
 58 
 59                     //返回输入流
 60                     InputStream in = connection.getInputStream();
 61 
 62                     //读取输入流
 63                     reader = new BufferedReader(new InputStreamReader(in));
 64                     StringBuilder result = new StringBuilder();
 65                     String line;
 66                     while ((line = reader.readLine()) != null) {
 67                         result.append(line);
 68                     }
 69                     show(result.toString());
 70                 } catch (MalformedURLException e) {
 71                     e.printStackTrace();
 72                 } catch (ProtocolException e) {
 73                     e.printStackTrace();
 74                 } catch (IOException e) {
 75                     e.printStackTrace();
 76                 } finally {
 77                     if (reader != null) {
 78                         try {
 79                             reader.close();
 80                         } catch (IOException e) {
 81                             e.printStackTrace();
 82                         }
 83                     }
 84                     if (connection != null) {//关闭连接
 85                         connection.disconnect();
 86                     }
 87                 }
 88             }
 89         }).start();
 90     }
 91 
 92     private void show(final String result) {
 93         runOnUiThread(new Runnable() {
 94             @Override
 95             public void run() {
 96                 textView.setText(result);
 97             }
 98         });
 99     }
100 }
MainActivity

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:id="@+id/activity_main"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:orientation="vertical">
 7 
 8     <EditText
 9         android:id="@+id/editText"
10         android:layout_width="match_parent"
11         android:layout_height="wrap_content"
12         android:ems="10"
13         android:inputType="textPersonName"
14         android:text="" />
15 
16     <Button
17         android:id="@+id/send_request"
18         android:layout_width="match_parent"
19         android:layout_height="wrap_content"
20         android:text="点击查询"
21         />
22 
23     <!--带滚动条的视图-->
24     <ScrollView
25         android:layout_width="match_parent"
26         android:layout_height="match_parent">
27 
28         <!--响应数据-->
29         <TextView
30             android:id="@+id/response_data"
31             android:layout_width="match_parent"
32             android:layout_height="wrap_content"
33             />
34 
35     </ScrollView>
36 
37 
38 </LinearLayout>
activity_main.xml

AndroidManifest.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.baiducs">
 4     <uses-permission android:name="android.permission.INTERNET"/>
 5     <application
 6         android:usesCleartextTraffic="true"
 7         android:allowBackup="true"
 8         android:icon="@mipmap/ic_launcher"
 9         android:label="@string/app_name"
10         android:roundIcon="@mipmap/ic_launcher_round"
11         android:supportsRtl="true"
12         android:theme="@style/AppTheme">
13         <activity android:name=".MainActivity">
14             <intent-filter>
15                 <action android:name="android.intent.action.MAIN" />
16 
17                 <category android:name="android.intent.category.LAUNCHER" />
18             </intent-filter>
19         </activity>
20     </application>
21 
22 </manifest>
AndroidManifest.xml

下面是服务器端

web结构

 

 这里主要就是一个dengluServlet调用方法查询数据库返回给Android端结果,上述MainActivity通过http请求访问到dengluServlet,下面是dengluServlet的代码,web端其余代码不在此给出,有需要的请留言。

 1 package com.jdbc.jss;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 import java.io.PrintWriter;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 import javax.servlet.ServletException;
11 import javax.servlet.ServletInputStream;
12 import javax.servlet.annotation.WebServlet;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 import com.jdbc.bean.Yiqing;
18 import com.jdbc.dao.yiqidao;
19 @WebServlet(name = "dengluServlet",urlPatterns = "/dengluServlet")
20 public class dengluServlet extends HttpServlet {
21 
22 
23     private static final long serialVersionUID = 1L;
24      public  dengluServlet() {
25             super();
26         }
27 
28     @Override
29     protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
30         response.setContentType("text/html;charset=utf-8");
31         request.setCharacterEncoding("utf-8");
32         response.setCharacterEncoding("utf-8");
33         PrintWriter out = response.getWriter();
34         String timeend = request.getParameter("timeend");
35         System.out.println(timeend);
36             //按时间查询
37         //String list =  yiqidao.findss(timeend);
38         ArrayList<String> list = new ArrayList<String>();
39         list = yiqidao.findss(timeend);
40         System.out.println(list);
41         out.write(list.toString());
42         out.flush();
43         out.close();
44      }   
45     @Override
46     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
47         // TODO Auto-generated method stub
48         doGet(request, response);
49         
50     }
51 }
dengluServlet

以上内容我在实现时出现过各种问题同时我也参考了许多博客,这里列出主要的几份博客,希望能解决大家实现过程中出现问题

https://blog.csdn.net/snadijssajskkj/article/details/50554903

https://blog.csdn.net/zfdabc_ok/article/details/98055166

https://blog.csdn.net/zhao_zi_ming_lc/article/details/78302601

https://www.jianshu.com/p/5eee1ef02700

 

posted @ 2020-03-19 21:37  DemonSlayer  阅读(1537)  评论(8编辑  收藏  举报