Java:尝试从服务器下载 jar 文件:线程 "main"java.io.IOException 中出现异常:服务器返回 HTTP 响应代码:URL 为 403

标签 java url https download httpwebresponse

我正在尝试从 URL 下载 Jar 文件。我的代码如下所示:


import java.io.FileOutputStream;
import java.io.IOException;

import java.io.PrintWriter;

import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;




public class Update {



    @SuppressWarnings({ "resource" })
    public Update() throws IOException {

        System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7");

        System.out.print("Update found, downloading...");




            URL tariff = new URL("https://someurl/license/Updated" + Main.newupdate + ".jar");

              ReadableByteChannel tar = Channels.newChannel(tariff.openStream());
              FileOutputStream fos = new FileOutputStream("Updated.jar");
              fos.getChannel().transferFrom(tar, 0, 1<<24);
...

但是,我总是收到错误: 线程“main”java.io.IOException中出现异常:服务器返回HTTP响应代码:URL的403

附加信息:我拥有该文件所在的服务器。是否可以更改我的 xamp 设置来防止此错误?

我尝试设置用户代理,但仍然不起作用。

最佳答案

我通过将代码更改为以下内容解决了问题:

URL url = new URL("https://someurl.io/license/Updated" + Main.newupdate + ".jar");
            String fileName = "Updated.jar";

            URLConnection urlConn = url.openConnection();
            urlConn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
            String contentType = urlConn.getContentType();

            System.out.println("contentType:" + contentType);

            System.setProperty("http.agent", "Chrome");
            InputStream in = urlConn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }

关于Java:尝试从服务器下载 jar 文件:线程 "main"java.io.IOException 中出现异常:服务器返回 HTTP 响应代码:URL 为 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60382784/

相关文章:

java 打印 var 的问题,抱歉再次发帖

Python命令提示符-自动提取链接

python - Tornado:从部分 URL 创建完整 URL

ssl - WSSE 认证悖论

java - Activity 上的两个 onclick 转换为 fragment

java - 如何优雅地取消嵌入式 Jetty 中死锁的 WEB 请求

javascript - 在 3000 端口上使用 https 的 Node.js socket.io

security - 当IE提示 “Only secure content is displayed”时,我能知道不安全内容的网址吗?

java - 解码期间的 JAXB::XML 验证

java - 对 URL 上的 GET 参数进行编码