→阿童沐

財富==支撐一個人生存多長時間的能力!

导航

Java解析来自于所请求的URL的XML流-

package com.commons;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.*;
import org.w3c.dom.Document;

public class XmlClass
{
    // 解析一个来自所请求的URL的XML文档
    public static Document getDocument(String urlString)
    {
        try
        {
            URL url = new URL(urlString);
            try
            {
                URLConnection URLconnection = url.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK)
                {
                    InputStream in = httpConnection.getInputStream();
                    try
                    {
                        DocumentBuilderFactory factory = DocumentBuilderFactory
                                .newInstance();
                        DocumentBuilder db = factory.newDocumentBuilder();
                        Document doc = db.parse(in);
                        return doc;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    System.out.println("HTTP connection response !=HTTP_OK");
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

posted on 2012-04-20 17:34  阿童沐  阅读(264)  评论(0)    收藏  举报