gpt4 book ai didi

java - 如何解码 Stack Exchange API 响应

转载 作者:行者123 更新时间:2023-11-30 09:08:21 24 4
gpt4 key购买 nike

我正在尝试检索堆栈交换 api 的响应,例如[ http://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow]

我正在使用以下代码来检索响应

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class RetrieveAllTag {

public static void main(String... args) {

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow");
HttpResponse response = null;

try {
response = httpClient.execute(httpGet);
InputStream content = response.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(content,"UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());

}
catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
finally {
httpClient.getConnectionManager().shutdown();
}
}
}

但是我得到的响应是解码形式的 ��n�� ����\f]as��DՊ��I��/��m(��*Ʃ����Kc����

我发现了类似的问题[ https://stackoverflow.com/questions/20808901/problems-with-decoding-stack-exchange-api-response] ,但我没有找到问题的任何答案。

如何解码api响应?

提前致谢。

最佳答案

内容已压缩。您需要通过解压缩流发送它,例如

import java.util.zip.GZIPInputStream;

...
InputStream content = response.getEntity().getContent();
content = new GZIPInputStream(content);
...

您还应该首先检查内容编码,如果编码实际上 gzip - 一些代理,则只将流包装到 GZIPInputStream透明地已经解压缩流。

参见 SOQuery.java对于完整示例,即使这是使用 java.net.HttpURLConnection 而不是 apache 客户端。

关于java - 如何解码 Stack Exchange API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23560740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com