写了个简单android的C/S应用,总结一下,方便自己下次使用也希望能够帮到学android的朋友们。
1. 软硬件准备
1.1 服务器端
使用Ubuntu 10.10(64位), jdk 1.6 和tomcat7。
1.2 Android客户端
使用Android4.1.2真机,开发使用了从android官网上下载的sdk和eclipse(win7的64位版本)。
2. 服务器开发
2.1 tomcat 配置运行
tomcat 运行很简单,直接附上shell命令。
tar -zxvfapache-tomcat-7.0.34.tar.gz
cdapache-tomcat-7.0.34/bin/
./startup.sh
2.2 servlet 代码及编译
由于我的目的只是写个小例子,所以就只是修改了下tomcat的样例代码。
代码路径:apache-tomcat-7.0.34/webapps/examples/WEB-INF/classes/HelloWorldExample.java
代码正文:
/*
*Licensed to the ApacheSoftware Foundation (ASF) under one or more
*contributor licenseagreements. See theNOTICE filedistributed with
* thiswork for additionalinformation regarding copyright ownership.
* The ASFlicenses this file to Youunder theApache License, Version 2.0
* (the"License"); youmay not use this file except in compliance with
* theLicense. You may obtain a copy of theLicense at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unlessrequired byapplicable law or agreed to in writing, software
*distributed under the License isdistributed on an "AS IS" BASIS,
* WITHOUTWARRANTIES OR CONDITIONSOF ANY KIND, either express or implied.
* See theLicense for the specificlanguage governing permissions and
*limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The simplest possible servlet.
*
* @author JamesDuncan Davidson
*/
publicclass HelloWorldExample extends HttpServlet {
privatestaticfinallongserialVersionUID= 1L;
@Override
publicvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)
throws IOException, ServletException
{
//打印从客户端传来的参数值
System.out.println("Testresults----->"+request.getParameter("test"));
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//回写
out.println("<html>");
out.println("<head>");
String title =rb.getString("helloworld.title");
out.println("<title>" +title +"</title>");
out.println("</head>");
out.println("<bodybgcolor=\"white\">");
// note that all links are createdtobe relative. this
// ensures that we can move thewebapplication that this
// servlet belongs to to adifferentplace in theurl
// tree and not have any harmfulsideeffects.
// XXX
// making these absolute till weworkout the
// addition of a PathInfo issue
out.println("<ahref=\"../helloworld.html\">");
out.println("<imgsrc=\"../images/code.gif\" height=24 " +
"width=24 align=rightborder=0 alt=\"viewcode\"></a>");
out.println("<ahref=\"../index.html\">");
out.println("<imgsrc=\"../images/return.gif\" height=24 " +
"width=24 align=rightborder=0alt=\"return\"></a>");
out.println("<h1>" +title +"</h1>");
out.println("</body>");
out.println("</html>");
}
}
然后就是编译,这里有两点需要注意。
1. javac 之前需要设置classpath。
命令:export CLASSPATH= apache-tomcat-dir/lib/servlet-api.jar(apache-tomcat-dir请换成相应的tomcat目录)
2. 要让改动生效要重起一下tomcat服务器。
命令:./shutdown.sh && ./startup.sh
3. Android客户端开发
3.1 应用代码
我使用了google IDE中的HelloWorld参考代码稍加改动,附源码如下(MainActivity.java)。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public classMainActivity extends Activity {
private static final String TAG ="TestAppMain";
//异步方式打开网络连接
privateclassHttpThreadextendsThread{
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnectionurlConnection = null;
try{
URL url = new URL("http://172.16.123.108:8080/examples/servlets/servlet/HelloWorldExample?test=123");
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in =urlConnection.getInputStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
String result = "";
String readLine = null;
while((readLine=bufferReader.readLine()) !=null){
result+= readLine;
}
Log.d(TAG,"back data: \n"+ result);
}catch(Exception e){
e.printStackTrace();
}finally{
urlConnection.disconnect();
}
}
}
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpThread().start();
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main,menu);
return true;
}
}
还需要在AndroidMenifest.xml中添加权限。
<uses-permissionandroid:name="android.permission.INTERNET"/>
3.2 运行结果
手机段打印出服务器发出的html文件内容,服务器端也能够接受到get方法发送的参数并打印出数值。
注:打印语句在 apache-tomcat-7.0.34/logs/catalina.out文件中。