java—如何将xml数据发送到当前端点的服务器

qvtsj1bj  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(288)

我试图读取一个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();

当前im硬编码字符串数据,但我想发送rest端点中的数据http://localhost:8080/登录如果我点击这个端点,我会得到一个xml

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

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

mxg2im7a

mxg2im7a1#

我不经常回答,但我想我遇到过这样的情况。如果我理解正确,您需要将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的简单方法

相关问题