在带有变量的java中卷曲POST请求

时间:2016-06-30 14:34:01

标签: java xml rest curl

所以我有这段代码,我试图使用之前开发的Web应用程序验证具有特定模式的xml。在网站上它给出了一个curl命令,我做了一些研究,尝试在java中执行它无济于事。我找到了一个名为httpclient的api但找不到POST的任何内容

问题的后半部分;如果这是正确的格式,那么它必须是我在curl命令中呈现xml变量的方式。

@POST
@Path("/Validate")
//Uncomment when testing with real xml
//@Produces("application/xml")
public String validate(@FormParam("xml") String xml)
{
    System.out.println(xml);
    System.out.println("validate");
    try {
        Process process = Runtime.getRuntime().exec( "curl -X POST --data-    urlencode 'xml=<hml>xml</hml>' http://miring.b12x.org/validator/ValidateMiring/ ");
        BufferedReader input = new BufferedReader(new     InputStreamReader(process.getInputStream()));
        String cmdXML="";
        String line=null;
        while((line=input.readLine())!=null)
        {
            cmdXML+=line;
        }
    } catch (IOException e) {
        logger.error("Something went wrong in validating "+ e);
        System.out.println("Error in validation");
    }
    return "stuff";
}

1 个答案:

答案 0 :(得分:0)

首先,当您的命令包含多个元素时,runtime.exec(...)需要String[]

Java API运行时: http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String[])

其次,您必须确保该命令适用于您:

curl -X POST --data-urlencode 'xml=<hml>xml</hml>' http://miring.b12x.org/validator/ValidateMiring/

最后,您必须指明命令curl的完整路径。

示例: /usr/bin/curl在Unix上或C:/Program Files/Curl/curl在Windows上

小心

在下面的代码中,您必须将<PATH_TO_CURL>替换为命令的实际路径curl

你能试试这段代码吗?

<强>代码

@POST
@Path("/Validate")
//Uncomment when testing with real xml
//@Produces("application/xml")
public String validate(@FormParam("xml") String xml)
{
    System.out.println(xml);
    System.out.println("validate");
    try {
        Runtime runtime = Runtime.getRuntime();
        String[] command = {"<PATH_TO_CURL>/curl", "-X", "POST", "--data-urlencode", "'xml=<hml>xml</hml>'", " http://miring.b12x.org/validator/ValidateMiring/"}
        Process process = runtime.exec(command);
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String cmdXML="";
        String line=null;
        while((line=input.readLine())!=null)
        {
            cmdXML+=line;
        }
    } catch (IOException e) {
        logger.error("Something went wrong in validating "+ e);
        System.out.println("Error in validation");
    }
    return "stuff";
}