创建两个项目
- Android项目: 用于发送数据到服务器
- web项目: 用于构建服务器端接收数据
代码
import android.util.Log;
import com.android.demo_filestream.studentdao.Student;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HttpSave{
String path = Constant.SERVEURL+"Servlet";
public HttpSave(Student student) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("stuId", student.getStuId());
params.put("stuName", student.getStuName());
params.put("stuSex", student.getStuName());
params.put("stuAge", student.getStuName());
params.put("stuHome", student.getStuName());
params.put("stuDept", student.getStuName());
sendGETRequest(path, params, "UTF-8");
}
private static boolean sendGETRequest(String path, Map<String, String> params, String ecoding) throws Exception{
int flag=0;
final StringBuilder url = new StringBuilder(path);
url.append("?");
for(Map.Entry<String, String> entry : params.entrySet()){
url.append(entry.getKey()).append("=");
url.append(URLEncoder.encode(entry.getValue(), ecoding));
url.append("&");
}
url.deleteCharAt(url.length() - 1);
System.out.println(url);
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(30000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
System.out.println("发送成功");
}else {
System.out.println("发送失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return true;
}
}
package com.idea.xxx;
import java.io.IOException;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.idea.S_T.Student;
import com.idea.daoimp.Studentimpl;
@WebServlet("/Servlet")
public class Servlet extends HttpServlet{
public Servlet() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Student student=new Student();
student.setStuId(req.getParameter("stuId"));
student.setStuName(req.getParameter("stuName"));
student.setStuSex(req.getParameter("男"));
student.setStuAge(22);
student.setStuHome(req.getParameter("stuHome"));
student.setStuDept(req.getParameter("stuDept"));
Studentimpl stu=new Studentimpl();
stu.save(student);
String stuId=req.getParameter("stuId");
System.out.println(stuId);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
public void init() throws ServletException {
super.init();
}
}