尝试访问图片网址时出现403错误

时间:2016-12-09 21:50:36

标签: java image url download

首先,我应该提一下,我试图在互联网上找到一个解决方案2天甚至更多,所以如果你想把我链接到另一个帖子,我很可能已经看过了。现在出现问题:

当我尝试下载图像时,使用某些链接我的代码可以正常工作,但有些会产生错误,例如,此链接会出错(以及我尝试从cdn.discordapp.com获取的所有其他链接): https://cdn.discordapp.com/attachments/235200958974394368/256888406645145602/output.jpg

在您查看代码之前,我还应该提一下它使用外部API,但您仍然可以理解其中的大部分内容,此外,我的URL始终是图片网址。

这是我的代码:

   try {
    url = new URL(event.getMessage().getContent().substring(12));
    openConnection = url.openConnection();
    String userCredentials = "username:password";
    String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
    openConnection.setRequestProperty ("Authorization", basicAuth);
    openConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
    openConnection.setRequestProperty("Request Method", "POST");
//  openConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    openConnection.setRequestProperty("Content-Language", "en-US");
    openConnection.setUseCaches(false);
    openConnection.setDoInput(true);
    openConnection.setDoOutput(true);
    if(openConnection.getContentLength() > 8000000) {
        event.getChannel().sendMessage(event.getAuthor().getAsMention()+" file size is too big.").queue();
        check = false;
    }
} catch (Exception e) {
    event.getChannel().sendMessage("Couldn't create a connection to the link, please recheck the link.").queue();
    check = false;
    e.printStackTrace();
}
if(check) {
    BufferedImage img = null;
    try {
        InputStream in = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1 != (n=in.read(buf)))
        {
            out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        img = ImageIO.read(new ByteArrayInputStream(response));
    } catch (Exception e) {
        event.getChannel().sendMessage(event.getAuthor().getAsMention()+" couldn't read an image from this link.").queue();
        e.printStackTrace();
    }
    JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
    jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    jpegParams.setCompressionQuality(0.1f);
    File file = new File("output.jpg");
    try {
        final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        writer.setOutput(new FileImageOutputStream(file));
        writer.write(null, new IIOImage(img, null, null), jpegParams);
        event.getChannel().sendFile(file, null).queue();
        file.delete();
    } catch (IOException e) {
        event.getChannel().sendMessage("Couldn't create/send the output image.").queue();
        e.printStackTrace();
    }
}

这是带有错误的堆栈跟踪(您可以忽略此行[23:21:06] [Fatal] [JDA]: One of the EventListeners had an uncaught exception及其中的任何内容):

`    java.io.IOException: Server returned HTTP response code: 403 for URL: https://cdn.discordapp.com/attachments/235200958974394368/256888406645145602/output.jpg
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at discordBot.Jpegify.execute(Jpegify.java:73)
at discordBot.Christina.onMessageReceived(Christina.java:163)
at net.dv8tion.jda.core.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:316)
at net.dv8tion.jda.core.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:64)
at net.dv8tion.jda.core.handle.MessageCreateHandler.handleDefaultMessage(MessageCreateHandler.java:129)
at net.dv8tion.jda.core.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:51)
at net.dv8tion.jda.core.handle.SocketHandler.handle(SocketHandler.java:38)
at net.dv8tion.jda.core.requests.WebSocketClient.handleEvent(WebSocketClient.java:665)
at net.dv8tion.jda.core.requests.WebSocketClient.onTextMessage(WebSocketClient.java:339)
at com.neovisionaries.ws.client.ListenerManager.callOnTextMessage(ListenerManager.java:352)
at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:262)
at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:240)
at com.neovisionaries.ws.client.ReadingThread.handleTextFrame(ReadingThread.java:965)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:748)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:110)
at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:66)
[23:21:06] [Fatal] [JDA]: One of the EventListeners had an uncaught exception
[23:21:06] [Fatal] [JDA]: Encountered an exception:
[23:21:06] [Fatal] [JDA]: java.lang.IllegalArgumentException: image == null!
at javax.imageio.IIOImage.<init>(Unknown Source)
at discordBot.Jpegify.execute(Jpegify.java:99)
at discordBot.Christina.onMessageReceived(Christina.java:163)
at net.dv8tion.jda.core.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:316)
at net.dv8tion.jda.core.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:64)
at net.dv8tion.jda.core.handle.MessageCreateHandler.handleDefaultMessage(MessageCreateHandler.java:129)
at net.dv8tion.jda.core.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:51)
at net.dv8tion.jda.core.handle.SocketHandler.handle(SocketHandler.java:38)
at net.dv8tion.jda.core.requests.WebSocketClient.handleEvent(WebSocketClient.java:665)
at net.dv8tion.jda.core.requests.WebSocketClient.onTextMessage(WebSocketClient.java:339)
at com.neovisionaries.ws.client.ListenerManager.callOnTextMessage(ListenerManager.java:352)
at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:262)
at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:240)
at com.neovisionaries.ws.client.ReadingThread.handleTextFrame(ReadingThread.java:965)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:748)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:110)
at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:66)`

当然,非常感谢任何帮助,对于长篇文章感到抱歉,这个问题真的让我感到紧张......

1 个答案:

答案 0 :(得分:2)

我明白了。你需要做几件事。首先,您需要在URLConnection上设置用户代理。然后你需要在URLConnection上打开openConnection。最后,如果您之前从URL获取流,则实际上需要从URLConnection获取getInputStream,因为这是您设置用户代理的位置。

这是我的代码,它的工作原理。将其复制并粘贴到名为Test.java的新文件中并尝试运行它。注意我注释掉了文件删除,因此您实际上可以看到文件下载

将它与您的活动和频道结合使用现在取决于您,祝您好运。

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;

public class Test {
    public static void main(String[] args) throws MalformedURLException, IOException {
        URL url = new URL("http://cdn.discordapp.com/attachments/235200958974394368/256888406645145602/output.jpg");
        URLConnection openConnection = url.openConnection();
        boolean check = true;

        try {

            openConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            openConnection.connect();

            if (openConnection.getContentLength() > 8000000) {
                System.out.println(" file size is too big.");
                check = false;
            }
        } catch (Exception e) {
            System.out.println("Couldn't create a connection to the link, please recheck the link.");
            check = false;
            e.printStackTrace();
        }
        if (check) {
            BufferedImage img = null;
            try {
                InputStream in = new BufferedInputStream(openConnection.getInputStream());
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int n = 0;
                while (-1 != (n = in.read(buf))) {
                    out.write(buf, 0, n);
                }
                out.close();
                in.close();
                byte[] response = out.toByteArray();
                img = ImageIO.read(new ByteArrayInputStream(response));
            } catch (Exception e) {
                System.out.println(" couldn't read an image from this link.");
                e.printStackTrace();
            }
            JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
            jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            jpegParams.setCompressionQuality(0.1f);
            File file = new File("output.jpg");
            try {
                final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
                writer.setOutput(new FileImageOutputStream(file));
                writer.write(null, new IIOImage(img, null, null), jpegParams);
                // event.getChannel().sendFile(file, null).queue();
                // file.delete();
            } catch (IOException e) {
                System.out.println("Couldn't create/send the output image.");
                e.printStackTrace();
            }
        }
    }

}