问题描述
- 【求助万能的csdn】android客户端传递一个类到服务器端的问题?毕设问题急
-
现在是希望将android客户端生成的Device类传到服务器端处理,Device类已经实现了serializable类。
android端:
public static void upload(String url_path, Device d) {
try {
URL url = new URL(url_path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setReadTimeout(2000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = conn.getOutputStream();
//GZIPOutputStream gzipout = new GZIPOutputStream(out);
ObjectOutputStream O_out = new ObjectOutputStream(out);
O_out.writeObject(d);
System.out.println(url_path + d.getDescribes()); //此处可以输出,可是
//gzipout.finish(); //服务器端没有收到请求。
O_out.flush();
O_out.close();
out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}}
url路径没问题。服务器端:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("--post--");
InputStream in = request.getInputStream();
//GZIPInputStream Gin = new GZIPInputStream(in);
ObjectInputStream O_in = new ObjectInputStream(in);
try {
Device device = (Device) O_in.readObject();
List list = new ArrayList();
list.add(device.getId());
list.add(device.getType());
list.add(device.getSize());
list.add(device.getDescribes());
String sql = "insert into device values(?,?,?,?)";
if(ju.updateByPreparedStatement(sql, list)) {
System.out.println("上传完成!");
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("上传错误");
}
}如果有请求,服务器端应该输出“--post--”,很明显服务器没有收到android的请求
请问这代码错在哪呢?还有要如何实现类的传输?这段代码对吗?谢谢!
解决方案
在你这段代码中,OutputStream out = conn.getOutputStream();
ObjectOutputStream O_out = new ObjectOutputStream(out);
O_out.writeObject(d);
应该写入的是已经序列化好的Device,然后用conn.connect();建立与服务器的连接,此时才是真正和服务器建立连接了,所以你缺少这个肯定收不到请求了,然后服务端接收到的流再反序列化成Device,即ok了
解决方案二:
不是,那个只是打开连接,真正的连接是.connect(),这时才会建立tcp连接
解决方案三:
URL url = new URL(url_path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setReadTimeout(2000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
OutputStream out = conn.getOutputStream();
ObjectOutputStream O_out = new ObjectOutputStream(out);
O_out.writeObject(d);
O_out.flush();
O_out.close();
out.close();
加个连接即可
解决方案四:
浏览器访问servlet服务看是否能收到请求。