• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.net.apihelpers;
6 
7 import org.json.JSONException;
8 import org.json.JSONObject;
9 
10 import org.chromium.net.UrlResponseInfo;
11 
12 /**
13  * A specialization of {@link InMemoryTransformCronetCallback} that interprets the response body as
14  * JSON.
15  */
16 public abstract class JsonCronetCallback extends InMemoryTransformCronetCallback<JSONObject> {
17     private static final StringCronetCallback STRING_CALLBACK =
18             new StringCronetCallback() {
19                 @Override
20                 protected boolean shouldFollowRedirect(
21                         UrlResponseInfo info, String newLocationUrl) {
22                     throw new UnsupportedOperationException();
23                 }
24             };
25 
26     @Override // Override to return the subtype
addCompletionListener( CronetRequestCompletionListener<? super JSONObject> listener)27     public JsonCronetCallback addCompletionListener(
28             CronetRequestCompletionListener<? super JSONObject> listener) {
29         super.addCompletionListener(listener);
30         return this;
31     }
32 
33     @Override
transformBodyBytes(UrlResponseInfo info, byte[] bodyBytes)34     protected JSONObject transformBodyBytes(UrlResponseInfo info, byte[] bodyBytes) {
35         String bodyString = STRING_CALLBACK.transformBodyBytes(info, bodyBytes);
36         try {
37             return new JSONObject(bodyString);
38         } catch (JSONException e) {
39             // As suggested by JSONException javadoc
40             throw new IllegalArgumentException("Cannot parse the string as JSON!", e);
41         }
42     }
43 }
44