java - 在 Java 中使用 curl 命令

标签 java curl

我有一个 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();

}
 }

针对您的问题。将curl映射到Java代码是最直接直观的,在使用的时候 流程 build 者。就这样写:

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");`

关于java - 在 Java 中使用 curl 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24053634/

相关文章:

linux - 对于本地运行的 scala spray 服务器,curl localhost 有效,但 curl <local ip> 获取 "Connection refused"

java - android studio 3.6.1调试找不到局部变量

curl - cURL 302 发现了什么?

php - 如何用php开发neteller Direct API?

php - 将 Paypal 返回字符串放入 mysql 数据库?

php - 缺少 Paypal 付款操作

java - 在Java中设计没有多重继承的类层次结构

java - 添加现有代码模型的方法

java - Apache-POI 忽略 Excel 工作表的行

java - JFlex 中可以继承吗?