繁体   English   中英

在java中使用curl命令

[英]Using curl command in java

我有一个 curl 命令要使用

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

任何人都可以告诉上述 curl 命令的等效 java 代码。

提前致谢

这里的示例显示了执行 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();

}
 }

对于您的问题。 在使用 Processbuilder 时,将 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");`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM