【问题标题】:Using curl command in java在java中使用curl命令
【发布时间】:2014-07-26 01:25:41
【问题描述】:

我有一个 curl 命令要使用

curl -s -d user.name=xxxx \
       -d file=yyyy \
       -d arg=-v \
       'http://localhost:zzzz/templeton/v1/pig'

谁能说出上述 curl 命令的等效 java 代码。

提前致谢

【问题讨论】:

  • 看一下http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html或看一下here
  • 使用 Java 发送 HTTP Post 的方法有很多种,只需 google 一下,这里有一个 SO 答案:stackoverflow.com/questions/4205980/…

标签: java curl


【解决方案1】:

这里有一个例子展示了执行 curl 的 Processbuilder。 这些代码部分在我的环境中运行良好。实际上,您将毫无问题地执行它。程序从网上获取图片,并保存为jpg文件。 jpg 文件保存在路径“/home/your_user_name/Pictures”中。

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

  public class ProcessBuilderTest {

public static void main(String arg[]) throws IOException {

    ProcessBuilder pb = new ProcessBuilder(
            "curl",
            "-s",
            "http://static.tumblr.com/cszmzik/RUTlyrplz/the-simpsons-season-22-episode-13-the-blue-and-the-gray.jpg ");

    pb.directory(new File("/home/your_user_name/Pictures"));
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream is = p.getInputStream();

    FileOutputStream outputStream = new FileOutputStream(
            "/home/your_user_name/Pictures/simpson_download.jpg");

    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] bytes = new byte[100];
    int numberByteReaded;
    while ((numberByteReaded = bis.read(bytes, 0, 100)) != -1) {

        outputStream.write(bytes, 0, numberByteReaded);
        Arrays.fill(bytes, (byte) 0);

    }

    outputStream.flush();
    outputStream.close();

}
 }

对于您的问题。将curl映射到Java代码是最直接直观的,使用时 流程建设者。就这么写吧:

curl -s -d user.name=xxxx \
-d file=yyyy \
-d arg=-v \
'htttp://localhost:zzzz/templeton/v1/pig'

成为

ProcessBuilder pb = new ProcessBuilder("curl", "-s","-d user.name=xxxx ","-d `file=yyyy","-d   rg=-v" ,"htttp://localhost:zzzz/templeton/v1/pig");`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2014-08-26
    相关资源
    最近更新 更多