Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

Using curl command in java

I have a curl command to use

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.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...