Speichern von XML aus Url und Lesen Sie es

Mache ich android App und brauche ich zum herunterladen eines xml Datei von einer URL und öffnen Sie Sie,
Wie kann ich das machen?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    File dir1 = getDir("xmls",Context.MODE_PRIVATE);//Creating an internal dir;
    System.out.println("dir1: " + dir1);

    //Saving The File
    try {
       URL url = new URL("http://www. the url of my xml .xml");
       //The server thinks this request is from an Opera browser!
       String userAgent = "Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1";
       System.out.println("Downloading ...");
       downloadFromUrl(url, dir1+"news.xml", userAgent);
       System.out.println("OK");
} catch (Exception e) {
        System.err.println(e);
        System.out.println("Entri pure nel catch");
    }
    //This is the path of the xml file that i have saved
    URL = dir1+"/news.xml" ; 
    ArrayList<HashMap<String, String>> songsList = 
                                       new ArrayList<HashMap<String, String>>();
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); //getting XML from UR
    Document doc = parser.getDomElement(xml); //getting DOM element
    //And then i do all the parsing
    NodeList nl = doc.getElementsByTagName(KEY_CATEGORIA);

Und die XMlParser Klasse ist wie folgt:

public class XMLParser_Categorie {

//constructor
public XMLParser_Categorie() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        //defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //return XML
    return xml;
}

Ich ändern müssen Sie diese Anweisung:

 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(url);
 HttpResponse httpResponse = httpClient.execute(httpPost);
 HttpEntity httpEntity = httpResponse.getEntity();
 xml = EntityUtils.toString(httpEntity);

Es eine Anfrage von einem lokalen Verzeichnis und nicht eine http-Anforderung.

InformationsquelleAutor JdO | 2013-05-02
Schreibe einen Kommentar