java 如何在java中发送curl请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27961528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:43:08  来源:igfitidea点击:

How to send a curl request in java

javacurl

提问by Amine CHERIFI

I'm using a java WebService to send a curl request, this is my request :

我正在使用 java WebService 发送 curl 请求,这是我的请求:

curl -d "input = a b c d" 'localhost:8090/jobs?appName=Test40&classPath=fr.aid.cim.spark.JavaWord&sync=true&timeout=1000000000'

I don't know wich lebrary i should use and how i can write it in java. Can you please show me how to do it.

我不知道我应该使用哪个 lebrary 以及如何用 java 编写它。你能告诉我怎么做吗?

Thank you.

谢谢你。

回答by DmitryKanunnikoff

If you need execute console command (curl in this case):

如果您需要执行控制台命令(在这种情况下为 curl):

Runtime runtime = Runtime.getRuntime();

try {
    Process process = runtime.exec("curl -d \"input = a b c d\" 'localhost:8090/jobs?appName=Test40&classPath=fr.aid.cim.spark.JavaWord&sync=true&timeout=1000000000'");
    int resultCode = process.waitFor();

    if (resultCode == 0) {
        // all is good
    } 
} catch (Throwable cause) {
    // process cause
}

UPDATE (according to your comment):Add folowing lines:

更新(根据您的评论):添加以下行:

System.out.println("is: " + IOUtils.toString(process.getInputStream()));
System.out.println("es: " + IOUtils.toString(process.getErrorStream()));

What is the output? IOUtils can be found here.

输出是什么?IOUtils 可以在这里找到。

回答by ikettu

You should take look Apache HttpClientlibrary. With HC Fluentcomponent you can write something like:

你应该看看Apache HttpClient库。使用HC Fluent组件,您可以编写如下内容:

Request.Post("http://localhost:8090/jobs?appName=Test40&classPath=fr.aid.cim.spark.JavaWord&sync=true&timeout=1000000000")
.execute().returnContent();

HC Fluent Javadocs

HC Fluent Javadocs