square/okhttp · error · IOException

Unexpected code

Error message

Unexpected code 

What it means

Recipe-level guard before parsing a GitHub gist with Moshi. After client.newCall(request).execute() for a specific gist ID, if the response is not 2xx the code throws java.io.IOException("Unexpected code " + response) and never reaches gistJsonAdapter.fromJson(...). Because the next step is JSON parsing, a silent 404-with-HTML-body would otherwise produce a Moshi JsonDataException, so this guard is the recipe's way of failing fast.

Source

Thrown at samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithMoshi.java:36

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public final class ParseResponseWithMoshi {
  private final OkHttpClient client = new OkHttpClient();
  private final Moshi moshi = new Moshi.Builder().build();
  private final JsonAdapter<Gist> gistJsonAdapter = moshi.adapter(Gist.class);

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://api.github.com/gists/c2a7c39532239ff261be")
        .build();
    try (Response response = client.newCall(request).execute()) {
      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

      Gist gist = gistJsonAdapter.fromJson(response.body().source());

      for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue().content);
      }
    }
  }

  static class Gist {
    Map<String, GistFile> files;
  }

  static class GistFile {
    String content;
  }

View on GitHub (pinned to 4fc0831380)

Solutions

  1. Authenticate with a GitHub token (Authorization: Bearer <token>) to lift the rate limit.
  2. Confirm the gist ID still exists by opening it in a browser.
  3. Check response.code() and Content-Type before attempting JSON parsing.
  4. Add a User-Agent header (the recipe omits one on this call).

Example fix

// before
try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  Gist gist = gistJsonAdapter.fromJson(response.body().source());
  ...
}

// after
try (Response response = client.newCall(request).execute()) {
  if (response.code() == 404) throw new IOException("Gist not found: " + request.url());
  if (response.code() == 403) throw new IOException("Rate-limited by GitHub");
  if (!"application/json".equalsIgnoreCase(
        String.valueOf(response.body().contentType()))) {
    throw new IOException("Unexpected content-type: " + response.body().contentType());
  }
  Gist gist = gistJsonAdapter.fromJson(response.body().source());
  ...
}
Defensive patterns

Strategy: validation

Validate before calling

// Pre-check rate limit budget and gist existence shape
Request req = new Request.Builder()
    .url("https://api.github.com/gists/c2a7c39532239ff261be")
    .header("Authorization", "Bearer " + token)
    .header("Accept", "application/vnd.github+json")
    .header("User-Agent", "MyApp/1.0")
    .build();
try (Response r = client.newCall(req).execute()) {
  if (r.code() == 404) throw new NoSuchElementException("gist missing");
  if (r.code() == 403) throw new RateLimitedException(r.header("X-RateLimit-Reset"));
  if (!"application/json".equalsIgnoreCase(String.valueOf(r.body().contentType()))) {
    throw new IllegalStateException("Expected JSON, got " + r.body().contentType());
  }
}

Try / catch

try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) {
    if (response.code() == 404) throw new NoSuchElementException("gist not found");
    if (response.code() == 403) throw new RateLimitedException(response.header("X-RateLimit-Reset"));
    throw new HttpException(response.code(), response.message());
  }
  Gist gist = gistJsonAdapter.fromJson(response.body().source());
}

Prevention

When it happens

Trigger: GET https://api.github.com/gists/c2a7c39532239ff261be. Fires on 404 (gist deleted or never existed), 403 (GitHub unauthenticated rate limit — 60/hr per IP), or 410. A network failure throws a different IOException before this line.

Common situations: The hard-coded gist ID (c2a7c39532239ff261be) being deleted by its owner; hitting the 60/hr unauthenticated limit while iterating; missing User-Agent (GitHub rejects); expecting the body to always be JSON and instead getting a 404 HTML page.

Related errors


AI-assisted analysis of square/okhttp@4fc0831380 (2026-08-04). Data as JSON: /data/errors/564427a7175aa22e.json. Report an issue: GitHub.