サーバー(Tomcatで実行中)に文字列を送信して、文字列を返そうとしています。クライアントは文字列を送信し、サーバーはそれを受信しますが、クライアントがそれを取得すると、文字列は null になります。
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();