java
40 lines · 9 steps
Calling the GitHub API with Java's HttpClient
A small client fetches a GitHub user over HTTP, maps status codes to exceptions, and deserializes JSON into a record.
Explained by
highlit
1public class GitHubUserClient {
2
3 private final HttpClient http = HttpClient.newBuilder()
4 .connectTimeout(Duration.ofSeconds(10))
5 .followRedirects(HttpClient.Redirect.NORMAL)
6 .build();
7
8 private final ObjectMapper mapper = new ObjectMapper()
9 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
10
11 public GitHubUser fetchUser(String username) throws IOException, InterruptedException {
12 HttpRequest request = HttpRequest.newBuilder()
13 .uri(URI.create("https://api.github.com/users/" + username))
14 .header("Accept", "application/vnd.github+json")
15 .header("User-Agent", "acme-service/1.0")
16 .timeout(Duration.ofSeconds(15))
17 .GET()
18 .build();
19
20 HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
21
22 int status = response.statusCode();
23 if (status == 404) {
24 throw new NoSuchElementException("No GitHub user named " + username);
25 }
26 if (status >= 400) {
27 throw new IOException("GitHub API returned " + status + ": " + response.body());
28 }
29
30 return mapper.readValue(response.body(), GitHubUser.class);
31 }
32
33 public record GitHubUser(
34 long id,
35 String login,
36 String name,
37 @JsonProperty("public_repos") int publicRepos,
38 @JsonProperty("html_url") String profileUrl) {
39 }
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A shared, pre-configured HttpClient with sensible timeouts is cheaper and safer than building one per request.
- 2Translating HTTP status codes into meaningful exceptions gives callers a clean, domain-oriented error contract.
- 3Records plus @JsonProperty give a compact, immutable target for JSON that tolerates unexpected fields.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/calling-the-github-api-with-java-s-httpclient-explained-java-7343/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.