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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM