如何上传,下载文件从tomcat服务器用用户名,密码摆动 [英] how to upload, download file from tomcat server with username,password in swing

查看:364
本文介绍了如何上传,下载文件从tomcat服务器用用户名,密码摆动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在swing中创建一个连接到本地运行的tomcat服务器的程序。使用用户名,密码验证,然后用户可以上传服务器目录中的文件。 ie.http://本地主机:8080 / uploadfiles。来自用户定义的文件路径,与下载到本地目录相同。

I want to make a program in swing which connect to tomcat server running locally. with username,password authentication, then user able to upload file in server directory. ie.http://localhost:8080/uploadfiles. from user defined file path , and same as download to the local directory.

推荐答案

这是一种可能性:
下载:

Here is one possibility: Download:

    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

Now, on the server side, you will need to distinguish between GET and POST requests and handle them accordingly. You will need a library to handle uploads, such as apache FileUpload

哦,在客户端,您将需要一个执行Base64编码的库,例如apache 公共编解码器

Oh, and on the client side, you will need a library that does Base64 encoding such as apache commons codec

这篇关于如何上传,下载文件从tomcat服务器用用户名,密码摆动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆