您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用用户名和密码从tomcat服务器上传,下载文件

如何使用用户名和密码从tomcat服务器上传,下载文件

这是一种可能性:下载:

    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请求并进行相应处理。您将需要一个库来处理上传,例如apacheFileUpload

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

其他 2022/1/1 18:15:21 有588人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶