我正在尝试使用Java访问此json文件:http://www.cloudpricingcalculator.appspot.com/static/data/pricelist.json。
但是当我阅读它时,有时它会给我一个JSON字符串(没关系),有时它会给我其他东西,而json.simple.parser会抛出一个Unexpected character(<) at position 0
。
根据我在stackOverflow上阅读的内容,可能是它返回XML而不是JSON。由于我的网址是“ json”,这怎么可能?
这是我正在使用的代码:
String baseUrl = "http://www.cloudpricingcalculator.appspot.com/static/data/pricelist.json";
...
URL url = new URL(this.baseUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String l;
String json = "";
System.out.println(url);
while((l=in.readLine()) != null){
System.out.println(l);
json+=l;
}
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(json);
并且日志
<
后跟许多方格和未知字符,例如ÿÕ[s›È]和错误
Unexpected character () at position 0.
解决方案如下:
您没有考虑从服务器返回的资源的压缩和编码。 HEAD
请求的响应如下:
rpax@machine:~$ HEAD http://www.cloudpricingcalculator.appspot.com/static/data/pricelist.json
200 OK
Cache-Control: public, max-age=600
Connection: close
Date: Mon, 21 Aug 2017 12:02:14 GMT
Age: 112
ETag: "n_s_jQ"
Server: Google Frontend
Content-Encoding: gzip <---- *HERE*
Content-Length: 7902
Content-Type: application/json
Expires: Mon, 21 Aug 2017 12:12:14 GMT
...
为避免此问题,您可以将url流包装到
GZIPInputStream中:
GZIPInputStream gis = new GZIPInputStream(url.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(gis));
// ...
执行
readline()
时返回的数据将被解压缩。