在java中使用curl命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24053634/
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
Using curl command in java
提问by Reddevil
I have a curl command to use
我有一个 curl 命令要使用
curl -s -d user.name=xxxx \
-d file=yyyy \
-d arg=-v \
'http://localhost:zzzz/templeton/v1/pig'
Can anybody tell equivalent java code for the above curl command.
任何人都可以告诉上述 curl 命令的等效 java 代码。
Thanks in advance
提前致谢
回答by CrimsonFantasy
Here a example show Processbuilder that executes curl. These section of code work fine in my environment. Actually, you will executes it with no problems. The program obtains the image from web, and save as a jpg file. The jpg file is saved at the path "/home/your_user_name/Pictures".
这里的示例显示了执行 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();
}
}
For your questions. It is the most directly and intuitively to map curl to Java code, when using Processbuilder. Just write as that:
对于您的问题。在使用 Processbuilder 时,将 curl 映射到 Java 代码是最直接、最直观的。就这样写:
curl -s -d user.name=xxxx \
-d file=yyyy \
-d arg=-v \
'htttp://localhost:zzzz/templeton/v1/pig'
become
变得
ProcessBuilder pb = new ProcessBuilder("curl", "-s","-d user.name=xxxx ","-d `file=yyyy","-d rg=-v" ,"htttp://localhost:zzzz/templeton/v1/pig");`