JSONObject 文本必须以“{”开头,位于 2 [character 3 line 1]

A JSONObject text must begin with '{' at 2 [character 3 line 1]

以下程序我正在尝试调用堆栈交换 api 以在 JSON 中获得响应。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://api.stackexchange.com/2.2/users/4614124?order=desc&sort=reputation&site=Whosebug");
    System.out.println(json.toString());
  }
}

当我 运行 这些时,我收到以下错误,但响应对象仅以 { .

开头
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 2 [character 3 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
    at org.json.JSONObject.<init>(JSONObject.java:184)
    at org.json.JSONObject.<init>(JSONObject.java:310)
    at JsonReader.readJsonFromUrl(JsonReader.java:28)
    at JsonReader.main(JsonReader.java:36)

来自 url 的响应使用 Gzip 压缩。您需要在读取输入流之前对其进行解压缩。这是通过用 GZIPInputStream 包装 InputStream 来完成的。

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    GZIPInputStream gis = new GZIPInputStream(is);
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(gis, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}