0

I have a curl request which i need to call from my java code.

curl -XGET 'abc.com:9200/datafinal/map/_search' -d '
{
   "query": {
    "filtered": { 
      "query": {
        "match": { "ORIG_PROVIDER_ID": 1 }
      },
      "filter": {
        "range": { "TRANSACT_DATE": { "gte": "2015-01-01 00:00:00.0" ,"lte": "2015-01-10 00:00:00.0"}}
      }
    }
  },
     "aggs" : {
        "amount_sum" : { "sum" : { "field" : "TOTAL_AMT" } }
    }
}
'

This is the curl request. how can i call it from java code? To form this exact code with httpurlconnection in java looks like a tough job with the request body.

1 Answers1

0
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class CURLTest {
    public void main(String[] args) throws IOException {
        sendData();
    }

public String sendData() throws IOException {
    // curl_init and url


    URL url = new URL( "Put the Request here");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    // CURLOPT_POST
    con.setRequestMethod("POST");

    // CURLOPT_FOLLOWLOCATION
    con.setInstanceFollowRedirects(true);

    String postData = "my_data_for_posting";
    con.setRequestProperty("Content-length",
            String.valueOf(postData.length()));

    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream output = new DataOutputStream(con.getOutputStream());
    output.writeBytes(postData);
    output.close();

    // "Post data send ... waiting for reply");
    int code = con.getResponseCode(); // 200 = HTTP_OK
    System.out.println("Response    (Code):" + code);
    System.out.println("Response (Message):" + con.getResponseMessage());

    // read the response
    DataInputStream input = new DataInputStream(con.getInputStream());
    int c;
    StringBuilder resultBuf = new StringBuilder();
    while ((c = input.read()) != -1) {
        resultBuf.append((char) c);
    }
    input.close();

    return resultBuf.toString();
}
}

I have no possibility to test this code right now but it should work that way.