Skip to content

Instantly share code, notes, and snippets.

@dhsrocha
Created July 19, 2020 08:43
Show Gist options
  • Save dhsrocha/525c0335b627e8ea67bd7d98a20750c3 to your computer and use it in GitHub Desktop.
Save dhsrocha/525c0335b627e8ea67bd7d98a20750c3 to your computer and use it in GitHub Desktop.
Java 8+ HTTP Client.
import io.swagger.v3.oas.models.PathItem.HttpMethod;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import lombok.val;
/**
* Utility HTTP 1.1 client for requesting to other external API.
*/
@Log
@NoArgsConstructor(staticName = "create")
public class HttpClient {
/**
* Extracts the content requested from a URL.
*
* @param url The URL to source from.
* @return The extraction content in string form.
* @since 1.0-SNAPSHOT.
*/
@SneakyThrows
public String sourceFrom(final String url) {
val conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(HttpMethod.GET.name());
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IllegalStateException(
"Not satisfiable status code: [" + conn.getResponseCode() + "]");
}
try (val stream = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
return stream.lines().collect(Collectors.joining());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment