第十四天 乐在其中-Android与远端之GET方式

          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;
	
	@Override
	protected 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();
		}
	}
	
	@Override
	public 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会打印以下结果:




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值