我正在学习android中的网络,以便我可以从网站API获取内容。我正在浏览Udacity教程,并了解了制作HttpURLConnection所需的这些代码行。但是如果我必须从Https URL中提取内容呢?请建议以下HttpsURL连接代码中需要进行哪些修改。
HttpURLConnection:
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
答案 0 :(得分:0)
readFromStream(inputStream);
这行代码负责阅读内容。在您发布的代码示例中,似乎是URL正在获取的JSON内容。 创建自己的readFromStream()实现,你就可以了。