Skip to content

Instantly share code, notes, and snippets.

@saada2006
Last active October 4, 2022 00:33
Show Gist options
  • Save saada2006/f38e6be4623da914d04960de3dff9057 to your computer and use it in GitHub Desktop.
Save saada2006/f38e6be4623da914d04960de3dff9057 to your computer and use it in GitHub Desktop.
import java.net.*;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
public class DeadstockTask {
public static void main(String[] args) {
// method 1: without HttpURLConnection
try {
// create a url connection
URL deadstock = new URL("https://www.deadstock.ca/products.json");
// our only goal here is to read it, so we can skip doing any fancy stuff besides getting an i/o connection
BufferedReader input = new BufferedReader(new InputStreamReader(deadstock.openStream()));
// since we are reading a json file, it would be best to read it into a string for further use (that is, if we were going to read the file)
String json = "";
// read line by line to get the file
while(true) {
String line = input.readLine();
if(line == null) {
break;
}
json += line;
}
System.out.println("Method 1: " + json);
input.close();
} catch(Exception e) {
e.printStackTrace();
}
// method 2: with HttpURLConnection
try {
URL url = new URL("https://www.deadstock.ca/products.json");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
System.out.println("Recevied code " + con.getResponseCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = "";
while(true) {
String s = reader.readLine();
if(s == null) {
break;
}
json += s;
}
reader.close();
System.out.println("Method 2: " + json);
} catch(Exception e) {
e.printStackTrace();
}
/*
// method 3: sockets
// unfortunately, I get 403 forbidden with this code
try {
SocketFactory factory = SSLSocketFactory.getDefault();
Socket socket = factory.createSocket("www.deadstock.ca", 443);
PrintWriter out = new PrintWriter(socket.getOutputStream(), false);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send our http request
out.print("GET /products.json https/1.1\r\n");
out.print("Host: www.deadstock.ca\r\n");
out.print("Accept: application/json\r\n");
out.print("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n");
out.print("\r\n");
out.flush();
String json = "";
// read line by line to get the file
while(true) {
String line = in.readLine();
if(line == null) {
break;
}
json += line + '\n';
}
System.out.println("Method 3: " + json);
} catch(Exception e) {
e.printStackTrace();
}*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment