尝试从URL获取Xml数据时,它返回null

时间:2011-08-02 08:14:06

标签: java android xml

我正在尝试获取xml数据并使用异步任务解析它。这是我做的: 在OnCreate方法中,我将url作为字符串。我测试了我的网址,它不会返回null。也有权连接到互联网。

            startDownload start = new startDownload();
            start.execute(url.toString());  

我的Async类:

protected class startDownload extends AsyncTask<String, Void, String>{
    @Override
    protected void onPreExecute() {

        eczaDialog = ProgressDialog.show(ListViewXML.this,"", "Loading...");
    }
    @Override
    protected String doInBackground(String... aurl) {
        try {
            URL url = new URL(aurl[0]);

            DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize(); ....

当我调试我的代码时,我看到这个doc变量返回null。我不明白问题出在哪里。我希望你能帮我找到谢谢。

1 个答案:

答案 0 :(得分:1)

您必须获取xml的内容。您可以使用此代码,在您创建XML对象后,代码将返回字符串中的内容:

public static String getStringPage(String url){
    StringBuffer stringBuffer = new StringBuffer();
    BufferedReader bufferedReader = null;
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    URI uri = null;
    HttpResponse httpResponse = null;
    InputStream inputStream = null;
    String HTMLCode = null;


    //Create client and a query to get the page
        httpClient = new DefaultHttpClient();
        httpGet = new HttpGet();

        //Set the query with the url in parameter
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        httpGet.setURI(uri);

        //Execute the query
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Create a buffer to get the page
        try {
            inputStream = httpResponse.getEntity().getContent();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        //Get the buffer caracters
    try {
        HTMLCode = bufferedReader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    while (HTMLCode!= null){
        stringBuffer.append(HTMLCode);
        stringBuffer.append("\n");
        try {
            HTMLCode = bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Return the string of the page code
    return stringBuffer.toString();
}