使用Apache HttpClient连接到Druid的Java客户端

时间:2016-09-13 04:30:06

标签: java apache http druid

我正致力于在Druid Server上摄取和查询数据。但是,当我查询我只是使用命令行如下:

curl -X 'POST' -H 'Content-Type:application/json' -d @quickstart/ingest_statistic_hourly_generate.json localhost:8090/druid/indexer/v1/task

任何人都可以告诉我利用Apache HttpClient的Java客户端将该查询发送到德鲁伊服务器以获得响应的方式。非常感谢。

1 个答案:

答案 0 :(得分:2)

我没有对此进行过测试,但是这应该会让你对这个做一个很好的想法

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class HTTPTestClient {

    public static void main(String[] args) throws Exception {
        String url = "http://localhost:8090/druid/indexer/v1/task";
        String content = new String(Files.readAllBytes(Paths.get("quickstart/ingest_statistic_hourly_generate.json")));

        HttpClient client = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost(url);

        post.addHeader("Accept", "application/json");
        post.addHeader("charset", "UTF-8");
        post.addHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(content));

        HttpResponse response = client.execute(post);
        System.out.println(response.getStatusLine());
        System.out.println("Response Code : " + response);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result);

    }
}