首页 > 解决方案 > Java:尝试从服务器下载 jar 文件:线程“主”java.io.IOException 中的异常:服务器返回 HTTP 响应代码:URL 的 403

问题描述

我正在尝试从 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);
...

但是,我总是得到错误: Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL

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

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

标签: javaurlhttpsdownloadhttpwebresponse

解决方案


我通过将代码更改为此解决了这个问题:

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();
            }

推荐阅读