Created
October 25, 2020 18:35
-
-
Save 4Kaylum/8051dfa255b6f98ac9391e9ef64dd0cb to your computer and use it in GitHub Desktop.
A lil example on using Java to make REST requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.Gson; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.net.URL; | |
import java.net.URLConnection; | |
// Let's make this class to represent our response from random.cat | |
class ImageObject { | |
public String file; | |
} | |
public class CatImage { | |
public static void main(String[] args) throws Exception { | |
// Open a connection to the website | |
URL site = new URL("https://aws.random.cat/meow"); | |
URLConnection siteConnection = site.openConnection(); | |
// Make a buffered reader so we can get the site's content | |
BufferedReader in = new BufferedReader(new InputStreamReader(siteConnection.getInputStream())); | |
StringBuilder sb = new StringBuilder(); | |
String inputLine; | |
// Read the site's input | |
while ((inputLine = in.readLine()) != null) { | |
sb.append(inputLine); | |
} | |
// Sick now we can close our reader | |
in.close(); | |
String websiteContent = sb.toString(); | |
// Let's grab some Json | |
Gson gson = new Gson(); | |
ImageObject image = gson.fromJson(websiteContent, ImageObject.class); | |
// And now we got our stuff! | |
System.out.println(image.file); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment