Search code examples
javadiscord-jda

How to use InspiroBot.me api?


I'm trying to implement a command into my bot, where it's supposed to let InspiroBot (from inspirobot.me) generate an inspirational quote (as an image, not a string) and send that image in the text channel. The url for this is http://inspirobot.me/api?generate=true , where another url is generated, which shows the generated image.

I'm completely new to api's, so following a random tutorial on the topic I tried the following code:

try {
    URLConnection connection = new URL("http://inspirobot.me/api?generate=true").openConnection();
    InputStream input = connection.getInputStream();
    System.out.println(connection.getContentType());
} catch (IOException e) {
    e.printStackTrace();
}

However, the returned content type is null, and trying to use getContent() results in an error as there is apparently no content. :/


Solution

  • You are trying to access http://inspirobot.me/api?generate=true which only redirects you to HTTPS version of the page - https://inspirobot.me/api?generate=true. It doesn't return anything else. Redirect responses have no body, that's why Content Type returned is null and you can't get anything useful from your InputStream.

    However, if you access HTTPS in the first place you get what you expected:

    try {
        URLConnection connection = new URL("https://inspirobot.me/api?generate=true").openConnection();
        InputStream input = connection.getInputStream();
        System.out.println(connection.getContentType());
    
        String pictureUrl = new BufferedReader(new InputStreamReader(input)).readLine();
        System.out.println(pictureUrl);
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Will give you:

    text/html; charset=utf-8
    https://generated.inspirobot.me/a/qlPBbxz1P5.jpg
    

    Second request should be performed to fetch the picture itself.

    P.S. URLConnection class you're trying to use is very old, low level and even not specific to HTTP, I suggest using some http client library like apache http client or HttpClient class introduced in Java 11.