简体   繁体   English

如何在Android中将URL内容解析为字符串

[英]How to parse URL content to string in android

I have a valid URL, but I cannot parse its content to a string like I do in normal Java. 我有一个有效的URL,但是无法像在普通Java中一样将其内容解析为字符串。 I am pretty new to android. 我对android很陌生。 Mostly I convert my normal Java code to android Java and this code works perfectly in Java NetBeans but not in Android Studio. 通常,我将普通的Java代码转换为android Java,并且此代码在Java NetBeans中完美运行,但在Android Studio中却不行。

PSThere are no errors or even warnings given by compiler / during run-time. PS在运行时,编译器/没有错误或警告。 It just doesn't work and when I check the String length for "weather" its 0. 它只是不起作用,当我检查“天气”的字符串长度为0时。

String weather="";
            try {
                weather = new Scanner(new URL("http://api.openweathermap.org/data/2.5/forecast?lat="+lat+"&lon="+longi+"&units=metric&mode=xml").openStream(), "UTF-8").useDelimiter("\\A").next();
            } catch (Exception e) {

            }

You can use Jsoup. 您可以使用Jsoup。 Look at its " cookbook " for tutorials and more information but here is a simple example: 查看其“ 食谱 ”以获取教程和更多信息,但这是一个简单的示例:

    String WeatherString; //Declare earlier in code - Before "onCreate" method.
@Override
        protected Void doInBackground(Void... unused) {
            org.jsoup.nodes.Document doc = null;
            try {
                doc = Jsoup.connect("http://api.openweathermap.org/data/2.5/forecast").get();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(); 
        }

            WeatherString = doc.select("dl#weather dt + dd + dt + dd ").first().text(); //Input here where the xml code is that you want to parse to a string

            return null;        
        }

This code is inside of an AsyncTask . 这段代码在AsyncTask内部。 Hope this helps. 希望这可以帮助。 And, again, refer to the "cookbook" on the Jsoup website for more info. 再次,请参阅Jsoup网站上的“食谱”以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM