我的外网IP 192.168.1.13
配置tomcat服务器:在我的电脑D盘新建一个虚拟目录liyewenweb,将tomcat中webapps\ROOT下
的WEB-INF目录复制到liyewenweb下,配置tomcat中conf下的server.xml ( 在后面<Host> </Host> 中
增加 <Context path="/liyewen" docBase="d:\liyewenweb"/> ), 配置tomcat中conf下的
web.xml ( 找到listings,并将下面的false改成true )。
在D盘liyewenweb目录下新建android.jsp,内容如下:
<% // 接收发送来的请求
String id = request.getParameter("id") ;
String password = request.getParameter("password") ;
%>
<%
if ("xingming".equals(id) && "mima".equals(password)) {
%>
true
<%
} else {
%>
false
<%
}
%>
新建一个Android项目:
在main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#3399ff">
<TextView
android:id="@+id/info"
android:gravity="center_horizontal"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="20dp"/>
</LinearLayout>
在MyWebDemo.java中:
package com.e.webproject;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MyWebDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
TextView info = (TextView) super.findViewById(R.id.info);
boolean flag = false ; // 成功与否的标记
try {
URL url = new URL("http", "192.168.1.13",80,
"/liyewen/android.jsp?id=xingming&password=mima");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
byte data[] = new byte[512];
int len = conn.getInputStream().read(data); // 输入流读取
if (len > 0) { // 已经读取到内容
String temp = new String(data, 0, len).trim();
flag = Boolean.parseBoolean(temp) ; // 取出里面的boolean型数据
}
conn.getInputStream().close() ;
} catch (Exception e) {
info.setText("WEB服务器连接失败!") ;
}
if(flag){
info.setText("用户李叶文登录成功!") ;
} else {
info.setText("用户登录失败!") ;
}
}
}
在AndroidManifest.xml中配置权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.e.webproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyWebDemo"
android:label="@string/title_activity_my_web_demo" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>