java - 如何在swing中使用用户名和密码从tomcat服务器上传、下载文件

标签 java http tomcat

我想在 swing 中制作一个连接到本地运行的 tomcat 服务器的程序。使用用户名,密码验证,然后用户可以上传服务器目录中的文件。即.http://localhost:8080/uploadfiles。从用户定义的文件路径,和下载到本地目录一样。

最佳答案

这是一种可能: 下载:

    URL url = new URL("http://localhost:8080/uploadfiles");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    try {
        con.addRequestProperty("Authorization",
                "Basic " + encode64(username + ":" + password));
        InputStream in = con.getInputStream();
        try {
            OutputStream out = new FileOutputStream(outFile);
            try {
                byte buf[] = new byte[4096];
                for (int n = in.read(buf); n > 0; n = in.read(buf)) {
                    out.write(buf, 0, n);
                }
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    } finally {
        con.disconnect();
    }

上传:

    URL url = new URL("http://localhost:8080/uploadfiles");
    HttpURLConnection con = (HttpURLConnection)uploadUrl.openConnection();
    try {
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.addRequestProperty("Authorization",
                "Basic " + encode64(username + ":" + password));
        OutputStream out = con.getOutputStream();
        try {
            InputStream in = new FileInputStream(inFile);
            try {
                byte buffer[] = new byte[4096];
                for (int n = in.read(buffer); n > 0; n = in.read(buffer)) {
                    out.write(buffer, 0, n);
                }
            } finally {
                in.close();
            }
        } finally {
            out.close();
        }
        int code = con.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            String msg = con.getResponseMessage();
            throw new IOException("HTTP Error " + code + ": " + msg);
        }
    } finally {
        con.disconnect();
    }

现在,在服务器端,您需要区分 GET 和 POST 请求并相应地处理它们。您将需要一个库来处理上传,例如 apache FileUpload

哦,在客户端,您将需要一个进行 Base64 编码的库,例如 apache commons codec

关于java - 如何在swing中使用用户名和密码从tomcat服务器上传、下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7608428/

相关文章:

java - 如何响应 REST API 版本不匹配的警告?

java - 可空孙子关联的左连接提取导致 hibernate 中的 NPE

java - 如何在解析复杂 XML 时尽量减少 XMLStreamReader 中 if else if 的使用

java - Android - 为什么使用接口(interface)被认为是 Activity 和 Fragment 之间通信的最佳实践?

android - 如何在android上支持HTTP持久连接

javascript - 需要使用同一连接从服务器进行多次推送

http - 将子域添加到本地主机 URL

angularjs - Siteminder: 'Unable to process SMSESSION cookie' 仅用于 GET 请求

java - 为什么我的 HTML validator 一直报告与页面编码不同的编码?

java.util.并发.ExecutionException : Failed to initialize component