当前位置:首页 > 编程技术 > 正文

java如何从网页获取xml文件

java如何从网页获取xml文件

要从网页获取XML文件,可以使用Java的`HttpURLConnection`类来发送HTTP请求并接收响应。以下是一个简单的示例,展示如何使用Java从指定URL获...

要从网页获取XML文件,可以使用Java的`HttpURLConnection`类来发送HTTP请求并接收响应。以下是一个简单的示例,展示如何使用Java从指定URL获取XML内容:

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class FetchXML {

public static void main(String[] args) {

String urlString = "http://example.com/path/to/xmlfile.xml"; // 替换为实际的XML文件URL

try {

URL url = new URL(urlString);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

// 检查HTTP响应码

int responseCode = connection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

最新文章