HttpPost請求Elasticsearch
package com.train.monitoring.Reptile_mobile_monitoring.util;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class ESConfig {
public String get(){
DefaultHttpClient httpClient = new DefaultHttpClient();
String url="http://101.236.57.141:5601/api/saved_objects/_find?type=index-pattern&per_page=10000";
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
// 執行請求
HttpResponse response=null;
JSONObject jsonObject=null;
try {
response = httpClient.execute(httpGet);
String json2 = EntityUtils.toString(response.getEntity(), "utf-8");
jsonObject = JSONObject.parseObject(json2);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 列印執行結果
System.out.println(jsonObject);
return null;
}
public static JSONObject post(String url){
DefaultHttpClient httpClient = new DefaultHttpClient();
/**
* curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
'
*/
// String url = "http://101.236.47.119:9200/redis-log-2018.07.26/doc/_search?pretty";
HttpPost httpPost = new HttpPost(url);
// 設定請求的header
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// String param="{"+
// "\"query\": { \"match_all\": {} },"+
// "\"from\": 10,"+
// "\"size\": 10"+
// "}";
String param="{"+
"\"query\": { \"match_phrase\": {\"biztype\":\"排隊的 代理IP為:\"} },"+
"\"from\": 1,"+
"\"size\": 9000"+
"}";
// String param="{"+
// " \"query\": {"+
// " \"bool\": {"+
// " \"should\": ["+
// " { \"match\": { \"biztype\": \"排隊的代理IP為:\" } }"+
// // " { \"match\": { \"address\": \"lane\" } }"+
// " ]"+
// " }"+
// " }"+
// "}";
// 設定請求的引數
JSONObject jsonParam = JSONObject.parseObject(param);
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
JSONObject jsonObject=null;
try {
// 執行請求
HttpResponse response = httpClient.execute(httpPost);
String json2 = EntityUtils.toString(response.getEntity(), "utf-8");
jsonObject = JSONObject.parseObject(json2);
} catch (Exception e) {
e.printStackTrace();
}
// 列印執行結果
return jsonObject;
}
}