所以我面临一些难以尝试,简单地说,从网页获取JSON文件,然后在Android上解析它。我已经构建了解析器,并在Eclipse中进行了测试(实际上,所有代码都在Eclipse中运行)。但是,当我运行HttpURLConnection并尝试在Android Studio中的字符串中检索JSON数据时,我最终得到没有异常和几乎为空的字符串(我想我得到的是第1,第2,第3和最后一个字符,但是不太确定)。我已经包含了以下代码的部分内容,并且
URL url = null;
HttpURLConnection urc = null;
try {
url = new URL(query);
urc = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urc.getInputStream());
jsoncontent = readStream(in);
System.out.println(jsoncontent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urc.disconnect();
}
readStream()的代码在
之下private static String readStream(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
is.close();
return sb.toString();
}
答案 0 :(得分:0)
以下是我上学期做的作业中的一小部分:
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "text/html");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
JSONObject searchResults = new JSONObject(in.readLine());
...
conn.disconnect();
您的代码中似乎缺少setRequestMethod(" GET")和setRequestProperty(" Accept"," text / html")。希望这会有所帮助。