我正在努力解决与http,java和stackexchange API相关的一些问题 将以下url视为字符串:
private static final String URLSTRING_2 = "http://freegeoip.net/json/";
如果我在浏览器中写这个网址,我会得到这个答案为json:
现在我试图用java和只有原生的libs来做这件事,因为我正在使用下面的代码片段到目前为止工作得很好......
如果我解析json并且我尝试获取密钥“country_name”的值,那么该代码段打印为指定的“新加坡”
public static void main(String[] args) throws Exception {
// Connect to the URL using java's native library
final URL url = new URL(URLSTRING_2);
final HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
final JsonParser jp = new JsonParser(); // from gson
final JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); // Convert the input stream to a json
// element
final JsonObject rootobj = root.getAsJsonObject(); // May be an array, may be an object.
final String country = rootobj.get("country_name").getAsString(); // just grab the zipcode
System.out.println("country_name: " + country);
}
我的浏览器输出以下json:
但如果我尝试解析json,我会得到一个异常,因为我从请求中得到了这个:
ý•@‡ž¼ÚRìØ1ôX`»V±H [<? - ¹” / + OI£•........
对于甚至不可读的东西......
你知道为什么吗?提前致谢
答案 0 :(得分:1)
StackOverflow API GZIP压缩其响应。您看到该非人类可读字符串的原因是您试图在不先解压缩GZIP压缩数据的情况下读取它。
您的浏览器能够读取此标头并进行解压缩。你的代码还没有。
您可以通过在响应中显示Content-Encoding header的值来确认是否使用了GZIP压缩。添加行
System.out.println(request.getContentEncoding());
将打印出来
gzip
幸运的是,修复问题非常简单。您需要在GZIPInputStream
:
InputStream
final JsonElement root = jp.parse(new InputStreamReader(new GZIPInputStream((InputStream) request.getContent()))); // Convert the input stream to a json
但是,我建议使用诸如Apache HTTPComponents Client之类的库来代替内置的Java类来发出HTTP请求。特别是,像这样的库将自动检测内容编码并为您进行解压缩。