我連接到Guardian的新聞源以下載JSON。每隔一段時間我都會返回JavaScript並導致錯誤。該URL存儲在一個靜態的最終字符串中,因此始終相同。我在調試器中看到的url對於JSON是正確的。事實上,如果我將url從調試器表達式窗口中複製出來並粘貼到瀏覽器中,我就會返回JSON。我認爲問題不在於衛報。我認爲我的連接代碼中的某些東西可能會以某種方式破壞url,而Guardian會默認發送JavaScript。但我真的不知道。奇怪的URL問題當連接到Guardian API
以下是在所有情況下使用的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文件的頂部,當它回來正確: { 「迴應」:{ 「狀態」: 「OK」, 「userTier」:「批准」, 「總」:203, 「的startIndex」:1, 「的pageSize」:10, 「當前頁」:1, 「頁」:21, 「ORDERBY」: 「最新」, 「結果」 :[{等等
而且這個是我回來當談到如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();
}
}
這很有趣。太棒了!我有一個NetGear路由器,我只是重置它,問題就消失了!如果它具有訪客功能,我不會使用它。任何想法可能會導致這種情況? – Glenn
不,對不起 - 我不太瞭解路由器的說實話。我剛剛注意到,在你的錯誤情況下的響應看起來像是從你的路由器,然後谷歌'http://192.168.3.1:10080/ui/dynamic/guest-login.html' –