Skip to content

Instantly share code, notes, and snippets.

@Hypro999
Last active January 16, 2020 09:37
Show Gist options
  • Save Hypro999/0fa533f7e9928bff009745a19a4ef85d to your computer and use it in GitHub Desktop.
Save Hypro999/0fa533f7e9928bff009745a19a4ef85d to your computer and use it in GitHub Desktop.
An example of how to make a GET request in Java then using the GSON library to format the response data (JSON).
import java.net.URL;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class GetRequest {
static String URL = ""; // Set this as required.
static String METHOD = "GET";
static String AUTH_STRING = ""; // Set this as required or comment it out.
static String getResponse(InputStream stream) throws IOException {
String buffer;
StringBuffer response = new StringBuffer();
BufferedReader res = new BufferedReader(new InputStreamReader(stream));
while ((buffer = res.readLine()) != null)
response.append(buffer);
return response.toString();
}
static void prettyPrint(String response) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
HashMap<String, Object> thing = gson.fromJson(response, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(gson.toJson(thing));
}
public static void main(String args[]) {
URL url;
try {
String response;
url = new URL(GetRequest.URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(GetRequest.METHOD);
conn.setDoOutput(false);
conn.setRequestProperty("Authorization", GetRequest.AUTH_STRING);
System.out.println("Response Code: " + conn.getResponseCode());
if (conn.getResponseCode() != 200)
response = GetRequest.getResponse(conn.getErrorStream());
else
response = GetRequest.getResponse(conn.getInputStream());
System.out.println("Response Body: " + response);
GetRequest.prettyPrint(response);
}
catch (MalformedURLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment