Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.File;
import java.net.URI;
import java.util.Scanner;
import java.time.Duration;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.InputStream;
import java.io.FileOutputStream​;
import java.net.Authenticator;
import java.net.ProxySelector;
import java.net.HttpURLConnection;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpClient;
import static java.lang.System.out;
import java.nio.file.StandardOpenOption;
import java.nio.file.StandardCopyOption;
public class HTTPDemo {
private static final String API_ENDPOINT = "https://onyxfx-api.herokuapp.com/nbaBasicStatBean?";
private static final String API_ENDPOINT2 = "http://api.giphy.com/v1/gifs/";
private static final String API_ENDPOINT2_ID = "yoJC2COHSxjIqadyZW";
private static final String API_ENDPOINT2_KEY = "ZtFzb5dH6w9aYjoffJQ0RqlAsS5s0xwR";
private static final HttpResponse.BodyHandler<String> asString = HttpResponse.BodyHandlers.ofString();
private static final HttpResponse.BodyHandler<Void> asDiscarded = HttpResponse.BodyHandlers.discarding();
private static final HttpResponse.BodyHandler<InputStream> asInputStream= HttpResponse.BodyHandlers.ofInputStream();
private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.followRedirects(HttpClient.Redirect.NORMAL)
.proxy(ProxySelector.getDefault())
.build();
//main
public static void main (String[] args) {
//so pedantic of java that we have to do this....
String firstName = null;
String surname = null;
String season1 = null;
String season2 = null;
if (args.length == 4) {
firstName = args[0]; // NBA Player first name
surname = args[1]; // NBA Player last name
season1 = args[2]; // Inquired Season #1
season2 = args[3]; // Inquired Season #2
}
else {
out.println("An invalid amount of arguments was supplied.");
return;
}
out.println("---------------------------------");
try {
// HTTP GET Request, Response (Pre-Java 11 API)
{
//HTTP GET REQUEST
var HTTP_CLIENT= (HttpURLConnection)
URI.create(
new StringBuilder(HTTPDemo.API_ENDPOINT)
.append("firstName=").append(firstName)
.append("&surname=").append(surname)
.append("&season=").append(season1)
.toString())
.toURL()
.openConnection();
HTTP_CLIENT.setRequestMethod("GET");
var HTTP_CLIENT2 = (HttpURLConnection)
URI.create( //Set the appropriate endpoint
new StringBuilder(HTTPDemo.API_ENDPOINT2)
.append(HTTPDemo.API_ENDPOINT2_ID)
.append("?api_key=").append(API_ENDPOINT2_KEY)
.append("&data")
.append("&type")
.append("&images")
.toString() )
.toURL()
.openConnection();
HTTP_CLIENT2.setRequestMethod("GET");
//HTTP RESPONSE
var HTTP_RESPONSE = HTTP_CLIENT.getInputStream();
var scn = new Scanner(HTTP_RESPONSE);
var json_sb = new StringBuilder();
while (scn.hasNext()) {
json_sb.append(scn.next());
}
var JSON = json_sb.toString();
if (HTTP_CLIENT2.getContentType().contains("json")) {
var stream_in = (InputStream​)(HTTP_CLIENT2.getContent());
var stream_out = new FileOutputStream​ (new File("response1.json"));
stream_in.transferTo(stream_out);
stream_in.close();
stream_out.close();
}
else
return; // suffice for now.
// HTTP STATUS
var statusCode = HTTP_CLIENT.getResponseCode();
var statusCode2 = HTTP_CLIENT2.getResponseCode();
// HANDLE RESPONSE
if (statusCode == 200 || statusCode == 201)
out.println("Success! -- Pre-Java 11 REST API Call\n" +
surname + ", " + firstName + " [" + season1 +"]\n" + JSON);
else
out.println("Failure! -- Pre-Java 11 REST API Call");
out.println("---------------------------------");
if (statusCode2 == 200 || statusCode2 == 201) {
out.println("Success! -- Pre-Java 11 REST API Call\n" + "Let's download the file!" );
}
else
out.println("Failure! -- Pre-Java 11 REST API Call");
};
out.println("---------------------------------");
// HTTP GET Request, Response (Java 11 APIs)
{
// HTTP GET REQUEST
var HTTP_REQUEST = HttpRequest.newBuilder()
.uri(URI.create( //Set the appropriate endpoint
new StringBuilder(HTTPDemo.API_ENDPOINT)
.append("firstName=").append(firstName)
.append("&surname=").append(surname)
.append("&season=").append(season2)
.toString() ) )
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.build();
var HTTP_REQUEST2 = HttpRequest.newBuilder()
.uri(URI.create( //Set the appropriate endpoint
new StringBuilder(HTTPDemo.API_ENDPOINT2)
.append(HTTPDemo.API_ENDPOINT2_ID)
.append("?api_key=").append(API_ENDPOINT2_KEY)
.append("&data")
.append("&type")
.append("&images")
.toString() ) )
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.build();
// SEND HTTP GET REQUEST, RECIEVE OBJECT FOR HTTP GET RESPONSE
var HTTP_RESPONSE = HTTPDemo.HTTP_CLIENT.send(HTTP_REQUEST, asString);
var HTTP_RESPONSE2 = HTTPDemo.HTTP_CLIENT.send(HTTP_REQUEST, asDiscarded);
var HTTP_RESPONSE3 = HTTPDemo.HTTP_CLIENT.send(HTTP_REQUEST2, asInputStream);
// HTTP STATUS CODE
var statusCode = HTTP_RESPONSE.statusCode();
var statusCode2 = HTTP_RESPONSE2.statusCode();
var statusCode3 = HTTP_RESPONSE3.statusCode();
// HANDLE RESPONSE
if (statusCode == 200 || statusCode == 201)
out.println("Success! -- Java 11 REST API Call\n" +
surname + ", " + firstName + " [" + season2 +"]\n" + HTTP_RESPONSE.body());
else
out.println("Failure! -- Java 11 REST API Call");
out.println("---------------------------------");
if (statusCode2 == 200 || statusCode2 == 201)
if (HTTP_RESPONSE2.body() == null)
out.println("Success! -- Java 11 REST API Call\n" +
surname + ", " + firstName + " [" + season2 +"]\n" + "Data was discarded.");
else
out.println("Failure! -- Java 11 REST API Call");
out.println("---------------------------------");
if (statusCode3 == 200 || statusCode3 == 201) {
out.println("Success! -- Java 11 REST API Call\n" + "Let's download the file! ");
var HTTP_STREAM = HTTP_RESPONSE3.body();
Files.copy(HTTP_STREAM, new File("response2.json").toPath(), StandardCopyOption.REPLACE_EXISTING);
HTTP_STREAM.close();
}
else
out.println("Failure! -- Java 11 REST API Call");
};
out.println("---------------------------------");
} catch (Exception e) { out.println("Failure: A " + e.getClass() + " was thrown " + e.getMessage()); };
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.