我正在连接到卫报的新闻提要以下载 JSON。我时不时地取回 JavaScript,它会导致错误。URL 存储在静态最终字符串中,因此始终相同。我在调试器中看到的 url 对于 JSON 是正确的。事实上,如果我从调试器表达式窗口中复制 url 并将其粘贴到浏览器中,我会返回 JSON。我不认为卫报有问题。我认为我的连接代码中的某些内容可能会以某种方式破坏 url,而 Guardian 默认向我发送 JavaScript。但我真的不知道。
这是在所有情况下都使用的 URL。注意格式-json:
static final String GuardianUrl = "http://content.guardianapis.com/search?format=json&show-fields=headline%2Cbody%2Cthumbnail%2CtrailText%2ClastModified&date-id=date%2Ftoday&api-key=mykey";
这是正确返回时 JSON 文件的顶部:{ "response":{ "status":"ok", "userTier":"approved", "total":203, "startIndex":1, "pageSize ":10, "currentPage":1, "pages":21, "orderBy":"newest", "results":[{ etc.
这就是我在 JavaScript 中得到的结果:
09-21 15:00:18.853: E/JSON Parser(22101): Error converting string to json <html><head> <script language='javascript' type='text/javascript'>function init(_frm) { if (_frm.sent.value == 0) { _frm.sent.value=1; _frm.submit(); } }</script></head><body onload=init(auth)><form name=auth action='http://192.168.3.1:10080/ui/dynamic/guest-login.html' METHOD=GET><input type=hidden name='mac_addr' value='e0:75:7d:d3:15:0a'><input type=hidden name='url' value='http://content.guardianapis.com/search?format=json&show-fields=headline%2Cbody%2Cthumbnail%2CtrailText%2ClastModified&date-id=date%2Ftoday&api-key=pdva9u6ac2rqsx9a7hexzrv3'><input type=hidden name='ip_addr' value='192.168.3.142'><input type=hidden id=sent value='0'><noscript><input type=submit value='continue'></noscript></form></body></html> ... etc
这是连接和下载文件的代码:
public String getJSONFromUrl(String _url) throws IOException {
URL url = new URL(_url);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// Making HTTP request
try {
//ByteArrayOutputStream out = new ByteArrayOutputStream();
//InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
if (builder.toString().length()>0)
json = builder.toString();
return json;
} finally {
connection.disconnect();
}
}