我在HttpURLConnection输出流中传递数据,但HttpServletrequest输入流为空

时间:2015-01-23 13:00:25

标签: servlets inputstream httpurlconnection

这是客户端代码

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”]

1 个答案:

答案 0 :(得分:0)

来拆分。问题出在&#34; /&#34;网址末尾的符号。它没有了。但在这种情况下,servlet已做出回应。