0

我正在尝试从服务器下载文件(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;

}

4

1 回答 1

0

如果没有有关异常的更多详细信息,很难说出发生了什么,但我猜您正在尝试访问 UI 线程上的网络。搜索如何使用和 AsyncTask 以执行此操作。它看起来像这样:

public class downloadFile extends AsyncTask<String, Void, String>{
    protected String doInBackground(String... params){
        yourCodeHere
    }


}
于 2013-07-08T22:04:53.857 回答