【问题标题】:Convert cURL to Java for SOAP Call将 cURL 转换为 Java 以进行 SOAP 调用
【发布时间】:2018-06-07 16:00:46
【问题描述】:

我正在实现一个 SOAP Web 服务,它正在处理一个 cURL 调用。我实现了以下this tutorial。该服务正在使用以下命令:

curl --header "content-type: text/xml" -d @request.xml http://localhost:8080/ws

当然,此操作必须不受命令提示符的影响,并且可以在必要时调用,因此我想将此服务与例如调用方法时的操作相关联。

目前是从网上找到的

        String url = "http://localhost:8080/ws";
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestProperty("Content-Type", "text/xml");
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

我认为它应该是一个 POST 方法,但是如何添加“request.xml”和“--header”?什么命令将完成 cURL 调用?还是我这样做完全错了,而且还有很长的路要走,有没有更简单的方法?

PS:我已经运行了一个 Web 服务,并且正在使用 Eclipse Oxygen。

【问题讨论】:

  • 有很多方法可以做到这一点。但“最佳实践”是:1)获取 SOAP 服务的“WSDL”,2)使用 IDE(如 Eclipse 或 NetBeans)生成“Web 服务客户端”,然后 3)使用自动生成的代码制作 Web服务电话。这是一个示例:help.eclipse.org/oxygen/…
  • 我有一个 wsdl 文件和服务正在运行,我正在使用 Eclipse Oxygen
  • 很好 - 听起来您已经完成了 80%(或更多)的工作。根据上面的链接,只需使用 Eclipse/JEE 版本生成“自上而下的 Web 服务客户端项目”。本教程也可能有所帮助:ibm.com/developerworks/webservices/tutorials/ws-jse/index.html

标签: java spring spring-boot curl soap


【解决方案1】:

将下面的行添加到您的代码末尾,它将完成这项工作。

OutputStream wr = new DataOutputStream(conn.getOutputStream());


    BufferedReader br = new BufferedReader(new FileReader(new File("request.xml")));

    //reading file and writing to URL
    System.out.println("Request:-");
    String st;
    while ((st = br.readLine()) != null) {
        System.out.print(st);
        wr.write(st.getBytes());
    }

    //Flush&close the writing to URL.
    wr.flush();
    wr.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String output;

    StringBuffer response = new StringBuffer();
    while ((output = in.readLine()) != null) {
        response.append(output);
    }

    in.close();


    // printing result from response
    System.out.println("Response:-" + response.toString());

【讨论】:

  • 我收到以下错误“构造函数 BufferedReader(FileReader) 未定义”,第二行带有“request.xml”
  • 在您的代码中添加完整路径@request.xml 文件位置。
  • 该文件位于项目文件夹的最高级别。所以我假设给它简单的 request.xml 应该可以工作。
  • "request.xml" 实际上是一个字符串,我什至无法编译,因为错误。
  • 成功了,非常感谢!!!我刚刚将new File("requestPDF.xml") 向上移动,而 nit 抱怨文件库,我导入了它,然后它就可以工作了。一条简单的线有 20 多条线!是不是太多了?没有更短/更简单的方法吗? PS:我可以从前端 html 进行相同的调用吗?我有一个 spring-boot 应用程序。
【解决方案2】:

虽然HttpURLConnection 可用于此目的,但SOAPConnection 专为没有 WSDL 的情况而设计。

下面的代码要简单得多:

SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();

SOAPMessage msg =
        MessageFactory.newInstance()
            .createMessage(null, Files.newInputStream(Paths.get("request.xml")));

SOAPMessage resp = conn.call(msg, "http://localhost:8080/ws");

resp.writeTo(System.out);

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 2013-03-19
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多