【问题标题】:Convert curl to httpGet将 curl 转换为 httpGet
【发布时间】:2016-03-20 07:35:57
【问题描述】:

我希望在 java 代码中使用以下 curl 请求。我看到我们可以使用httpget来调用rest服务。

这是我的 curl 命令:

curl -XGET 'localhost:9200/indexname/status/_search' -d '{"_source": {"include": [ "field1", "name1" ]}, "query" : {"term": { "Date" :"2000-12-23T10:12:05" }}}'

如何将该命令放入我的 HttpGet httpGetRequest = new HttpGet(....);

请指教。谢谢。

【问题讨论】:

标签: java json curl http-get


【解决方案1】:

您可以使用HttpURLConnection此代码是我认为它适用于您的示例:

public void get() throws IOException{
    //Create a URL object.
    String url = "localhost:9200/indexname/status/_search";
    URL getURL = new URL(url);

    //Establish a https connection with that URL.
    HttpsURLConnection con = (HttpsURLConnection) getURL.openConnection();

    //Select the request method, in this case GET.
    con.setRequestMethod("GET");

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());

    String parameters = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}";

    //Write the parameter into the Output Stream, flush the data and then close the stream.
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    System.out.println("\nSending 'GET' request to URL : " + url);
    int responseCode;
    try {
        responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);
    } catch (Exception e) {
        System.out.println("Error: Connection problem.");
    }

    //Read the POST response.
    InputStreamReader isr = new InputStreamReader(con.getInputStream());
    BufferedReader br = new BufferedReader(isr);

    StringBuffer response = new StringBuffer();

    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        //Save a line of the response.
        response.append(inputLine + '\n');
    }
    br.close();

    System.out.println(response.toString());
}

如果这不起作用,那是因为我一定是输入错误的参数,还是试试吧

【讨论】:

    【解决方案2】:

    -X GET and -d 组合导致您的数据以 application/x-www-form-urlencoded 格式附加到 URL。

    因此,我建议如下使用URLEncoder

    String host = "localhost:9200/indexname/status/_search";
    String data = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}";
    String url = host + "?" + URLEncoder.encode(data, "UTF-8");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 2017-06-05
      • 2016-01-08
      • 2018-03-28
      • 2021-03-27
      • 2019-11-12
      • 2016-05-20
      相关资源
      最近更新 更多