我正在从 java 客户端程序向 Servlet 发送请求,如下所示,
URL url = new URL("http://localhost:8080/TestWebProject/execute");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(httpCon.getOutputStream());
out.writeUTF("hello");
out.writeUTF("World");
ByteArrayOutputStream bos;
File baseFile = new File("C:\\Users\\jp\\Desktop\\mdn.txt");
if (!baseFile.exists())
{
System.out.println("File Not Found Correctly");
}
FileInputStream fis = new FileInputStream(baseFile);
byte[] fileBytes = new byte[1024];
bos = new ByteArrayOutputStream();
while (true)
{
int ch = fis.read(fileBytes);
if (ch != -1)
{
bos.write(fileBytes, 0, ch);
}
else
{
break;
}
}
bos.close();
fis.close();
out.write(bos.toByteArray());
out.writeInt(10);
out.close();
* ** * ** * ** *伺服器端* ** * ** * ** *
InputStream is = (InputStream) req.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println("NAME US :" + dis.readUTF());
System.out.println("NAME US 1:" + dis.readUTF());
File f = new File("D:\\temp2.txt");
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
byte[] fileBytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while (true)
{
int ch = dis.read(fileBytes);
if (ch != -1)
{
bos.write(fileBytes, 0, ch);
}
else
{
break;
}
}
fos.write(bos.toByteArray());
System.out.println(dis.readInt());
我得到输出作为 Hello World 文件也成功复制到提到的位置 temp2.txt
我在 System.out.println(dis.readInt()); 行遇到问题 当 EOF 到达时。
我在哪里做错了,以及如何从 DataInputStream 读取数据。
谢谢。