4月25,中雨。“游子春衫已试单,桃花飞尽野梅酸。怪来一夜蛙声歌,又作东风十日寒。”

1、服务器端

(1)工程视图

(2)web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>ServerForGET</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <servlet><servlet-name>ServletForGet</servlet-name><servlet-class>com.servlet.get.ServletForGet</servlet-class>  </servlet>  <servlet-mapping><servlet-name>ServletForGet</servlet-name><url-pattern>/ServletForGet</url-pattern>  </servlet-mapping></web-app>
(3) ServletForGet.java
package com.servlet.get;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;//@WebServlet("/ServletForGet")public class ServletForGet extends HttpServlet {private static final long serialVersionUID = 1L;           public ServletForGet() {        super();            }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");String age = request.getParameter("age");System.out.println("name: " + name);System.out.println("age: " + age);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}

(4)运行http://192.168.23.1:8080//ServerForGET/ServletForGet?name=大头&age=20

注意观察eclipse的console会打印以下结果:

注意:IP:192.168.23.1:8080,是WIFI共享精灵设置的虚拟的无线网卡的IP,IP自然由虚拟的无线路由分配,使用手机连接,会自动给手机分配同一网段的IP:如:192.168.23.2

因为在android模拟器中访问本机中的tomcat服务器时,注意:不能写localhost,因为模拟器是一个单独的手机系统,所以要写真是的IP地址。否则无法访问到服务器。
2、手机端代码
(1)工程视图


(2) MainActivity.java
package com.androidgetmethod;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText titleText;private EditText lengthText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);titleText = (EditText) findViewById(R.id.title);lengthText = (EditText) findViewById(R.id.length);}public void save(View v) {String title = titleText.getText().toString();String length = lengthText.getText().toString();try {boolean result = false;result = UserInformationService.save(title, length);if (result) {Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();} else {Toast.makeText(this, R.string.fail, Toast.LENGTH_LONG).show();}} catch (Exception e) {e.printStackTrace();Toast.makeText(this, "Exception error", Toast.LENGTH_LONG).show();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
(3) UserInformationService.java
package com.androidgetmethod;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;public class UserInformationService {public static boolean save(String title, String length) throws Exception {String path = "http://192.168.23.1:8080/ServerForGET/ServletForGet";Map<String, String> params = new HashMap<String, String>();params.put("name", title);params.put("age", length);return sendGETRequest(path, params, "UTF-8");}private static boolean sendGETRequest(String path, Map<String, String> params, String encoding) throws Exception {StringBuilder sb = new StringBuilder(path);if (params != null && !params.isEmpty()) {sb.append("?");for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append("=");sb.append(URLEncoder.encode(entry.getValue(), encoding));sb.append("&");}sb.deleteCharAt(sb.length() - 1);}HttpURLConnection conn = (HttpURLConnection) new URL(sb.toString()).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");if (conn.getResponseCode() == 200)return true;return false;}}
(4) activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/title" />    <EditText        android:id="@+id/title"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/length" />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:numeric="integer"         android:id="@+id/length"/>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="save"        android:text="@string/button" /></LinearLayout>
(5) strings.xml
<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">AndroidGetMethod</string>    <string name="hello_world">Hello world!</string>    <string name="action_settings">Settings</string>        <string name="title">name</string>    <string name="length">age</string>    <string name="button">save</string>    <string name="success">Succeeded to save</string>    <string name="fail">Failed to save</string></resources>
(6)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.androidgetmethod"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="8" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.androidgetmethod.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.INTERNET"/></manifest>
3、 安卓模拟器运行结果

eclipse的console会打印以下结果:


4、手机运行结果-手机截屏

eclipse的console会打印以下结果:




更多相关文章

  1. 用命令行启动android模拟器及安装apk
  2. Cocos2dx-- 手机游戏时不锁屏
  3. ADB工具的使用
  4. 修改Android模拟器的IMEI号
  5. Android安全分析挑战:运行时篡改Dalvik字节码
  6. 导出已安装到手机中程序的apk文件
  7. 执行命令mm出错以及运行adb shell出现insufficient permissions
  8. Android(安卓)Studio下HierarchyViewer的使用
  9. ROOT android 原理 基于(zergRush)

随机推荐

  1. Android五子棋算法简单实现
  2. Maven学习之 在Android项目上启用maven
  3. Android面试之Activity生命周期
  4. 安卓应用平台想要反超iOS?在中国好好表现
  5. 摘抄:Android:应用程序的生命周期
  6. Android(安卓)4.3 安全提升,Set-UID-Root
  7. android内部存储器和外部存储器
  8. 教你如何开发一款实用的完整Android(安卓
  9. Android的Socket 通信
  10. 百度地图的基本使用