java 使用java程序从链接下载xml文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13873308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a xml file from a link using a java program
提问by Malexion
I am trying to create a Java program that starts up, downloads an xml file from a http web address http://api.eve-central.com/api/marketstatand saves it to a set location so I can then parse it for the data I want.
我正在尝试创建一个启动的 Java 程序,从 http 网址http://api.eve-central.com/api/marketstat下载一个 xml 文件并将其保存到设置的位置,以便我可以解析它我想要的数据。
What I would like to know is how do I download this document from this link in java for a standard computer application?
我想知道的是,如何从 Java 中的此链接为标准计算机应用程序下载此文档?
回答by Kumaran
Did you try the XML SAX parser provide by Java?
您是否尝试过 Java 提供的 XML SAX 解析器?
Here is a sample code:
这是一个示例代码:
import java.net.URL;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
URL url = new URL("http://www.example.com/book.xml");
InputStream stream = url.openStream();
Document doc = docBuilder.parse(stream);
回答by Alexandre Lavoie
This function will get you the full content from the URL :
此功能将从 URL 中获取完整内容:
public String getURLContent(String p_sURL)
{
URL oURL;
URLConnection oConnection;
BufferedReader oReader;
String sLine;
StringBuilder sbResponse;
String sResponse = null;
try
{
oURL = new URL(p_sURL);
oConnection = oURL.openConnection();
oReader = new BufferedReader(new InputStreamReader(oConnection.getInputStream()));
sbResponse = new StringBuilder();
while((sLine = oReader.readLine()) != null)
{
sbResponse.append(sLine);
}
sResponse = sbResponse.toString();
}
catch(Exception e)
{
e.printStackTrace();
}
return sResponse;
}
Hope this helps!
希望这可以帮助!
回答by Shamis Shukoor
The response of the URL will contain the xml, you just have to type cast it to a String and parse for the required data
URL 的响应将包含 xml,您只需将其类型转换为 String 并解析所需的数据