【问题标题】:How can i send XML data to my server which is present end point如何将 XML 数据发送到当前端点的服务器
【发布时间】:2021-07-14 10:31:12
【问题描述】:

我正在尝试读取 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();

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

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

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

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

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

    我想您可以使用 Marshaller 将 JOSN 转换为 POJO 对象(或者转换为 JSONObject),然后将其 Marshaller 输出为 XML。对于一个简单的解决方案,我建议使用 Jackson(另外,如果您使用的是 Spring Boot Jackson 之类的工具)
    马文

    <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);
    

    我认为这个问题和你的问题很接近:simple-method-to-convert-json-to-xml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多