【问题标题】:How do I use curl in Java to make a call to a url?如何在 Java 中使用 curl 来调用 url?
【发布时间】:2018-11-01 08:57:53
【问题描述】:

我正在使用以下 CURL 命令将响应保存为 .pdf 格式:

curl -d "@name_of_xmlFile.xml" -X POST http:url/ -o name_of_response_pdfFile.pdf

如何使用 java 进行调用并将响应生成的 pdf 文件保存在特定文件夹中。

【问题讨论】:

    标签: java rest curl selenium-webdriver rest-assured


    【解决方案1】:

    欢迎来到堆栈溢出!

    这里的问题是 curl 是一个 Linux 命令。因为 Java 旨在一次编写并在任何地方(在任何机器上)运行,所以 java 不能直接使用 curl 等命令,默认情况下每个操作系统都不存在这些命令。

    因此,您需要包含其他地方的附加功能。

    我个人喜欢使用Unirest,这是一个很好的简单轻量级框架,可以帮助在 Java 中使用 Rest。

    祝你好运!

    【讨论】:

      【解决方案2】:

      您也可以在不使用 curl 的情况下在 Java 中执行帖子(不确定是否必须使用 curl)

      取自this文章:

      private void doPost() throws Exception {
      
          String url = "http:url/";
          URL obj = new URL(url);
          HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
      
          //add reuqest header
          con.setRequestMethod("POST");
      
          String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
      
          // Send post request
          con.setDoOutput(true);
          DataOutputStream wr = new DataOutputStream(con.getOutputStream());
          wr.writeBytes(urlParameters);
          wr.flush();
          wr.close();
      
          int responseCode = con.getResponseCode();
          System.out.println("\nSending 'POST' request to URL : " + url);
          System.out.println("Post parameters : " + urlParameters);
          System.out.println("Response Code : " + responseCode);
      
          BufferedReader in = new BufferedReader(
                  new InputStreamReader(con.getInputStream()));
          String inputLine;
          StringBuffer response = new StringBuffer();
      
          while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
          }
          in.close();
      
          //print result
          System.out.println(response.toString());
          // could ewually save to file rather than to stdout.
      
      }
      

      要发送正文,您可以尝试this

      如果使用 curl 是硬性要求,您可以使用 Runtime.getRuntime().exec(command);,如 here 所示,但请注意,这不一定是可移植的(例如,如果未安装 curl)并且如果正在运行的命令可能不安全没有以某种方式验证以防止不良行为者运行任意命令等......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-29
        • 2011-02-04
        • 2016-06-11
        • 2010-11-27
        • 2017-12-04
        • 1970-01-01
        • 2020-01-30
        相关资源
        最近更新 更多