在Java中为curl命令创建包装器类

时间:2018-08-28 17:34:13

标签: java curl wrapper

我试图用Java写一个包装器类,该类将发出请求并处理以下curl命令的响应。

curl命令为:

curl  -XPOST 'http://sda.tech/earl/api/processQuery' -H 'Content-Type:application/json' -d"{\"nlquery\":\"Who is the president of Russia?\"}"

3 个答案:

答案 0 :(得分:0)

您可以使用ProcessBuilder:
https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

我在CommandLineProcess类中使用它(构造函数完成所有工作):

private Process p;

public Process getProcess() {
    return p;
}

public
CommandLineProcess
(String[] commandWithParams, String executionDirectory, boolean waitFor)
{
    ProcessBuilder pb = new ProcessBuilder(commandWithParams);
    pb.directory(new File(executionDirectory));

    try {

        p = pb.start();
        if (waitFor) {
            p.waitFor();
        }

    } catch (IOException e) {
        Log.getInstance().error(e.getMessage());
    } catch (InterruptedException e) {
        Log.getInstance().error(e.getMessage());
    }
}

答案 1 :(得分:0)

我看不出写卷曲包装纸的目的。您可以使用现有的类URL,HttpClient或RestClient。

答案 2 :(得分:0)

假设您必须使用cURL而不是任何现成的Java HTTP客户端,则可以创建一个简单的包装器,该包装器将使用Java的Process API来调用基础的{{1 }}可执行文件。

像这样的一个非常简单的客户端:

cURL

然后可以像这样简单地完成对端点的调用:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class Curl {

    public enum HttpMethod { GET, PUT, POST, DELETE }

    private final String endpoint;
    public String getEndpoint() { return endpoint; }

    private final HttpMethod method;
    public HttpMethod getMethod() { return method; }

    private final String data;
    public String getData() { return data; }

    private final Map<String, String> headers;
    public Map<String, String> getHeaders() { return headers; }

    private Curl(String endpoint, HttpMethod method, String data, Map<String, String> headers) {
    this.endpoint = endpoint;
    this.method = method;
    this.data = data;
    this.headers = headers;
    }

    public String call() throws IOException, InterruptedException {
    List<String> command = new ArrayList<>();

    command.add("curl");
    command.add("-s");
    command.add("-X");
    command.add(method.name());
    command.add("\"" + endpoint + "\"");

    if (headers != null && !headers.isEmpty()) {
        StringBuilder builder = new StringBuilder();
        builder.append("\"");
        headers.keySet().forEach(s -> builder.append(s).append(":").append(headers.get(s)));
        builder.append("\"");
        command.add("-H");
        command.add(builder.toString());
    }

    if (data != null) {
        command.add("-d");
        command.add("\"" + data + "\"");
        command.add(data);
    }

    return doCurl(command.toArray(new String[0]));
    }

    private String doCurl(String[] args) throws IOException, InterruptedException {
        Process process = new ProcessBuilder(args)
        .redirectErrorStream(true)
        .start();

        String lines;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"))) {
            lines = reader.lines().collect(Collectors.joining("\n"));
    }
    process.waitFor();
        return lines;
    }

    public static class Builder {

        private String endpoint;
        private HttpMethod method;
        private String data;
        private Map<String, String> headers;

        public Builder(String endpoint) {
            this.endpoint = endpoint;
    }

    public Builder method(HttpMethod method) {
            this.method = method;
            return this;
    }

    public Builder data(String data) {
            this.data = data;
            return this;
    }

    public Builder headers(Map<String, String> headers) {
            this.headers = headers;
            return this;
    }

    public Curl create() {
            if (endpoint == null) {
        throw new IllegalArgumentException("Endpoint cannot be null");
        }

        if (method == null) {
            throw new IllegalArgumentException("HTTP method cannot be null");
        }
        return new Curl(endpoint, method, data, headers);
    }

    }

}

按照我之前所说的那样,请先打个招呼,我不明白为什么您不想使用Java组件(例如Java 9及更高版本具有本机HTTP客户端https://docs.oracle.com/javase/9/docs/api/jdk/incubator/http/HttpClient.html)的原因,但是我想这是进行某种分配,因此您可能需要使用的选项可能会受到限制。

我仅针对您希望使用的用例尝试了上述方法,但我看不出这在其他情况下也行不通。