如何将XML数据发送到我的服务器,这是目前的终点



我正在尝试读取json并以XML的形式将其发送回服务器。我能够成功地读取json,但我需要从我的端点中读取的内容发送一个xml

URL url = new URL("https://xxxx.xxx/xxxx/post");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/xml");
http.setRequestProperty("Accept", "application/xml");
String data = "<?xml version="1.0" encoding="utf-8"?>n<Request>n    <Login>login</Login>n    
<Password>password</Password>n</Request>";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();

目前我正在对字符串数据进行硬编码,但我想发送位于我的rest端点中的数据http://localhost:8080/login如果我达到这个端点,我会得到一个XML

<ArrayList>
<item>
<Login>1000<Login>
<Password>Pwd<Password>
</item>
</ArrayList>

我如何读取此端点并将其用作字符串数据

我不经常回答,但我想我遇到过这样的情况。如果我理解正确,您需要将JSON字符串转换为XML

我想您可以使用Marshaller将JOSN转换为POJO对象(或者转换为JSONObject(,然后将其编组为XML。对于一个简单的解决方案,我建议使用Jackson(此外,如果您使用的是类似Spring Boot的产品,Jackson会捆绑在其中(
Maven

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>

假设我们有一个类似JSON的:

[{"id":1,"name":"cat food"},{"id":2,"name":"dog food"}]

我们可以创建一个Java类,如:

class MappingObject{
public Integer id;
public String name;
//Getters and setters 
...
}

现在我们可以使用Marshaller将其转换为POJO,然后再转换为XML。

ObjectMapper objectMapper = new ObjectMapper();
List<MappingObject> parsedDataList= objectMapper.readValue(result, new TypeReference<List<MappingObject>>(){});
XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(reparsedDataList);
System.out.println("This is the XML version of the Output : "+xml);

我认为这个问题与您的问题很接近:将json转换为xml的简单方法

最新更新