我正在尝试调用stack exchange的api来获取我可以解析为JsonObject的stackoverflow用户数据,但是我得到的数据是不可读的垃圾。
这是我的代码:
String urlName = "https://api.stackexchange.com/2.2/users?site=stackoverflow";
URL url = new URL(urlName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
conn.disconnect();
我做错了吗?我已经按照示例代码进行了操作,但我看不出我在做什么不同
答案 0 :(得分:2)
问题是从https://api.stackexchange.com/2.2/users?site=stackoverflow
收到的内容是使用GZip压缩的。因此,您看到的不可读垃圾实际上是响应的压缩体。并非响应中的所有内容都将被压缩(某些站点可能选择不压缩它们),因此您需要检查它们是否存在。这可以使用
conn.getContentEncoding()
将此应用于您的代码会为您提供:
String urlName = "https://api.stackexchange.com/2.2/users?site=stackoverflow";
URL url = new URL(urlName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
InputStream inputStream = conn.getInputStream();
if ("gzip".equals(conn.getContentEncoding())) {
// Is compressed using GZip: Wrap the reader
inputStream = new GZIPInputStream(inputStream);
}
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
conn.disconnect();