【发布时间】:2015-03-22 12:41:05
【问题描述】:
这是客户端代码
public static void uploadFiles() {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get(Parameter.UPLOAD_FILES_DIR), "{*.dat}")) {
for (Path path : ds) {
System.out.println(path);
URL url = new URL(Parameter.UPLOAD_URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setConnectTimeout(1000 * 20);
conn.setReadTimeout(1000 * 20);
send(conn, path);
receive(conn);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void send(HttpURLConnection conn, Path path) throws Exception {
try (
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(path.toFile()))
) {
byte[] buffer = new byte[1024];
int c = 0;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
out.flush();
}
}
public static void receive(HttpURLConnection conn) throws Exception {
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) {
throw new Exception("Uploader response code: " + conn.getResponseCode());
}
}
}
这里是 Servlet 代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post request");
System.out.println(request.getContentLength());
try (BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
) {
String str;
while ((str = br.readLine()) != null) {
System.out.print(str);
}
} catch (Exception ex) {
ex.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()))) {
bw.write("Close connection!!!");
}
}
当我在服务器控制台中运行客户端代码时出现
发布请求 -1
request.getContentLength() 总是返回 -1 为什么我不能向 servlet 发送字节?这是包含我要发送的字节的文件 ["192","2","3","4","5","6","7","8","9","US"] ["194","2", "3","4","5","6","7","8","9","US"]
【问题讨论】:
-
一定要用
HttpURLConnection吗?那里有更舒适的图书馆。使用conn.setFixedLengthStreamingMode()或conn.setChunkedStreamingMode()可能会更好? -
忘记添加,客户端收到响应并在 System.out 中打印“关闭连接!!!”
-
不幸的是,使用 HttpURLConnection 是基本要求,比如不使用 conn.setFixedLengthStreamingMode()、conn.setChunkedStreamingMode()
-
已解决。问题出现在 url 末尾的“/”符号中。它不存在。但在这种情况下,servlet 已经响应了。
标签: servlets inputstream httpurlconnection