gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:06:51 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com