我正在尝试将字符串发送到服务器(在 tomcat 上运行)并让它返回字符串。客户端发送字符串,服务器接收它,但是当客户端取回它时,字符串为空。
doGet() 应该设置 String in = 来自客户端的输入。但是 doPost() 在 = null 中发送字符串。
为什么?我会假设 doGet() 在 doPost() 之前运行,因为它是由客户端首先调用的。
服务器:
private String in = null;
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
try{
ServletInputStream is = request.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
in = (String)ois.readObject();
is.close();
ois.close();
}catch(Exception e){
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
try{
ServletOutputStream os = response.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(in);
oos.flush();
os.close();
oos.close();
}catch(Exception e){
}
}
客户:
URLConnection c = new URL("***********").openConnection();
c.setDoInput(true);
c.setDoOutput(true);
OutputStream os = c.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject("This is the send");
oos.flush();
InputStream is = c.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
System.out.println("return: "+ois.readObject());
ois.close();
is.close();
oos.close();
os.close();