我正在尝试从服务器下载文件(Json),但由于某种原因我的代码不起作用。我在清单中给了应用程序互联网权限,网址是正确的(至少当我简单地将其复制并粘贴到浏览器时它可以工作)......有人可以看到这里有什么问题吗?我用 try/catch 包围了下载,但它总是抛出异常。
提前感谢您的帮助!!
private String downloadFile() throws IOException {
String toReturn = "";
URL url = new URL(urlDefault + itemToSearch);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
System.out.println("Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream is = new BufferedInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
toReturn += line;
}
br.close();
is.close();
conn.disconnect();
} else {
throw new IllegalStateException("HTTP response: " + responseCode);
}
return toReturn;
}