在elipse中创建一个Web 工程, 重写do get或者do post方法 ,接收android客户端的数据。
这是我写的一个简单的注册的服务器端代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name" );
String password = request.getParameter("password");
System.out.println("用户名:" + name + "||密码:" + password );
//链接数据库
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =(Connection) DriverManager
.getConnection("jdbc:mysql://localhost:3306/musicdb?user=root&password=root");
Statement sta = (Statement) con.createStatement();
//注册 插入数据到数据库
PreparedStatement psta = (PreparedStatement)con.prepareStatement("insert into usertable values (? ,? )");
psta.setString(1, name);
psta.setString(2, password);
psta.execute();
//打印数据库中所有用户名和密码
ResultSet res = (ResultSet) sta.executeQuery("select * from usertable");
while(res.next()){
System.out.println("yonghuming :" + res.getString("name"));
System.out.println("pass : " + res.getString("password"));
android 端
private String SERVER_URL = "http://192.168.1.106:8080/Web/servlet/NetServlet";
inname = (EditText) findViewById(R.id.addname);
inpassword = (EditText) findViewById(R.id.addpassword);
add_user = (Button) findViewById(R.id.add_user);
add_user.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String mname = inname.getText().toString();
String mpass = inpassword.getText().toString();
Map userinfo = new HashMap();
userinfo.put("name", mname);
userinfo.put("password", mpass);
try {
register(SERVER_URL, userinfo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//通过URL拼接的 用户名和密码 发送给服务端
private void register(String SERVER_URL, Map param)
throws Exception {
StringBuilder sb = new StringBuilder(SERVER_URL);
sb.append("?");
for (Map.Entry entry : param.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue())
.append("&");
}
sb.deleteCharAt(sb.length() - 1);
String newurl = sb.toString();
URL url = new URL(newurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
Toast.makeText(MainActivity.this, "连接成功", 1).show();
}
}