我有一个curl请求,我需要从我的java代码中调用。
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" } }
}
}
'
这是卷曲请求。我怎么能从java代码中调用它?要在java中使用httpurlconnection形成这个确切的代码,看起来对请求体来说是一项艰巨的任务。
答案 0 :(得分: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();
}
}
我现在无法测试此代码,但它应该以这种方式工作。