此项目实现网络通信,android手机客户端去请求PC服务端,将PC上mysql中的数据显示在手机上。
PC服务端用JavaWeb写了个servlet,android手机客户端请求这个servlet,由servlet执行查询数据,并返回给手机客户端,服务器为Tomcat。
为了更清楚的展示,咱们现在mysql建一个测试表test
create table test(
name varchar(20) primary key
);
插入几条记录,我们这里插入汉字,遇到乱码,我们可以去解决。
insert into test values('张三');
insert into test values('李四');
insert into test values('王五');
插入成功
闲话少说,直接上代码:
PC服务端
我用MyEclipse建立了一个JavaWeb项目,这个项目中主要由一个数据查询类DBManager.java和一个servlet(loadMessage.java)组成
DBManager.java
package com.njue.DBManager;
import java.awt.List;
import java.sql.*;
import java.util.ArrayList;
import org.omg.CORBA.Object;
public class DBManager {
;
String userName="root";
String password="123456";
Connection conn=null;
Statement stmt=null;
String url="jdbc:mysql://localhost:3306/mysql";
ArrayList<String> list=new ArrayList<String>();
String sql;
public DBManager(){
sql="select * from test;";
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,userName,password);
stmt=conn.createStatement();
ResultSet rst=stmt.executeQuery(sql);
while(rst.next()){
//String name=new String(rst.getString("name").getBytes("latin1"), "UTF-8");
String name=new String(rst.getString("name").getBytes("latin1"), "GB2312");// 这句可要可不要,以你不出现乱码为准
//也可不用转化,直接写成String name=rst.getString("name");
list.add(name);
}
rst.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<String> getList(){
return list;
}
}
loadMessage.java
package com.amaker.servlet;
import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.njue.DBManager.DBManager;
public class loadMessage extends HttpServlet {
public loadMessage() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8" );
PrintWriter out = response.getWriter();
String message="";
DBManager db=new DBManager();
ArrayList<String> list=db.getList();
for(int i=0;i<list.size();i++){
message=message+list.get(i)+"\r\n";
}
out.print(message);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void init() throws ServletException {
// Put your code here
}
}
Android手机客户端代码:
AndroidClientActivity.java
package com.njue.androidClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidClientActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.tv);
// 查询返回结果
String result = HttpUtil.queryStringForPost("http://10.0.2.2:8080/androidWeb/servlet/loadMessage");
//String result = HttpUtil.queryStringForPost("http://122.88.34.123:8080/androidWeb/servlet/loadMessage");
tv.setText(result);
}
}
HttpUtil.java
package com.njue.androidClient;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
// 基础URL
// 获得Get请求对象request
public static HttpGet getHttpGet(String url){
HttpGet request = new HttpGet(url);
return request;
}
// 获得Post请求对象request
public static HttpPost getHttpPost(String url){
HttpPost request = new HttpPost(url);
return request;
}
// 根据请求获得响应对象response
public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException, IOException{
HttpResponse response = new DefaultHttpClient().execute(request);
return response;
}
// 根据请求获得响应对象response
public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException, IOException{
HttpResponse response = new DefaultHttpClient().execute(request);
return response;
}
// 发送Post请求,获得响应查询结果
public static String queryStringForPost(String url){
// 根据url获得HttpPost对象
HttpPost request = HttpUtil.getHttpPost(url);
String result = null;
try {
// 获得响应对象
HttpResponse response = HttpUtil.getHttpResponse(request);
// 判断是否请求成功
if(response.getStatusLine().getStatusCode()==200){
// 获得响应
result = EntityUtils.toString(response.getEntity());
//result=new String(result.getBytes("8859_1"),"GB2312"); 这句可要可不要,以你不出现乱码为准
return result;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result = "网络异常!";
return result;
} catch (IOException e) {
e.printStackTrace();
result = "网络异常!";
return result;
}
return null;
}
}
当然还得在AndroidManifest.xml中加入网络访问权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
需要注意的写服务器的主机号时,千万不能写localhost或者127.0.0.1,因为Android模拟器虽然和服务端程序在同一台电脑上,但两个毕竟是独立的系统,我们可以用10.0.2.2去访问本机。
运行结果:
这是在模拟器上运行,有的同学有这样的想法,把ip改成自己电脑真实的Ip,把客户端拿到真机上去实验,但运行后会发现会显示“网络异常”,不能访问。这里涉及到了网络方面的问题,其实也非常简单。下篇博客将会详细的讲解,去解决这个问题。
补充:上传两个项目,不禁可以访问mysql,也可以访问Access数据库。
下载地址:http://download.csdn.net/detail/pzhtpf/4388157