{"id":"0bcc1be7d4c0e31f","repo":"square/okhttp","slug":"unexpected-code-0bcc1b","errorCode":null,"errorMessage":"Unexpected code ","messagePattern":"Unexpected code ","errorType":"exception","errorClass":"IOException","httpStatus":null,"severity":"error","filePath":"samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java","lineNumber":157,"sourceCode":"\n    client = new OkHttpClient.Builder()\n            .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager())\n            .build();\n  }\n\n  public void run() throws Exception {\n    Request request = new Request.Builder()\n        .url(\"https://publicobject.com/helloworld.txt\")\n        .build();\n\n    try (Response response = client.newCall(request).execute()) {\n      if (!response.isSuccessful()) {\n        Headers responseHeaders = response.headers();\n        for (int i = 0; i < responseHeaders.size(); i++) {\n          System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n        }\n\n        throw new IOException(\"Unexpected code \" + response);\n      }\n\n      System.out.println(response.body().string());\n    }\n  }\n\n  public static void main(String... args) throws Exception {\n    new CustomTrust().run();\n  }\n}\n","sourceCodeStart":139,"sourceCodeEnd":168,"githubUrl":"https://github.com/square/okhttp/blob/4fc083138014aba3d0078f5c26d1ce84815fa984/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java#L139-L168","documentation":"Recipe-level guard inside a client built with a custom trust store (HandshakeCertificates trusting only Comodo RSA, Entrust Root, and Let's Encrypt X3 roots). The recipe first dumps response headers, then throws java.io.IOException(\"Unexpected code \" + response) for non-2xx. Important: if the server's chain does NOT trace to one of the three trusted roots, you never reach this line — you get SSLHandshakeException (cert path validation failure) earlier. Reaching this line means trust succeeded and the response is an ordinary non-2xx.","triggerScenarios":"GET https://publicobject.com/helloworld.txt with the three-CA trust store. Reaches this line when the cert chain IS trusted but the response is 4xx/5xx. If the chain were untrusted (e.g. site moved to a Google/AWS cert) the call fails at handshake with 'unable to find valid certification path to requested target'.","commonSituations":"Commenting out .addPlatformTrustedCertificates() (as shipped) then trying to reach sites whose chain is not one of the three CAs — that is a handshake failure, not this error; site legitimately returns 404/503; cert rotated to a chain outside the three.","solutions":["If you see SSLHandshakeException, uncomment .addPlatformTrustedCertificates() or add the missing root CA.","If you actually reach this line, handle response.code() as a normal HTTP error.","For production, load your trust anchors from a bundled PEM resource rather than hard-coding three CAs."],"exampleFix":"// before\nif (!response.isSuccessful()) {\n  // prints headers first, then throws\n  throw new IOException(\"Unexpected code \" + response);\n}\n\n// after\nif (!response.isSuccessful()) {\n  throw new IOException(\"HTTP \" + response.code()\n      + \" (trust was OK; non-2xx from origin)\");\n}\n// and if you are seeing handshake errors instead, enable platform trust:\n//   new HandshakeCertificates.Builder()\n//       .addPlatformTrustedCertificates()\n//       .addTrustedCertificate(myOrgRoot)\n//       .build();","handlingStrategy":"try-catch","validationCode":"// Pre-validate that your trust store covers the target's chain\n// (otherwise you will get SSLHandshakeException, not the 'Unexpected code' line)\n// Use openssl s_client -connect host:443 -showcerts to see the chain issuer roots\n// and ensure each root is in your HandshakeCertificates.Builder.","typeGuard":null,"tryCatchPattern":"try {\n  Response response = client.newCall(request).execute();\n  if (!response.isSuccessful()) throw new HttpException(response.code(), response.message());\n} catch (SSLHandshakeException e) {\n  // chain does not trace to one of the three trusted roots\n  throw new TrustException(\"Untrusted chain — add the missing root or enable platform trust\", e);\n}","preventionTips":["Add .addPlatformTrustedCertificates() for general browsing, or list every root your endpoints use.","Load PEMs from bundled resources, not hard-coded strings, for maintainability.","Recognise that handshake failures (untrusted chain) are a different exception from the HTTP-status guard.","Test against each endpoint after restricting the trust store."],"tags":["okhttp","http-status","custom-trust","tls","java"],"analyzedSha":"4fc083138014aba3d0078f5c26d1ce84815fa984","analyzedAt":"2026-08-04T19:09:04.639Z","schemaVersion":2}