从url下载Json

时间:2013-07-08 21:57:47

标签: android http url download

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

}

1 个答案:

答案 0 :(得分:0)

如果没有关于异常的更多细节,很难说是什么,但我的猜测是你试图访问UI线程上的网络。搜索如何使用和AsyncTask以执行此操作。它看起来像这样:

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


}