maven
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
bulk
/**
* { "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }
* @return
*/
private static String buildDelete(JSONObject json,String index,String type,String id){
StringBuffer sb = new StringBuffer();
String str="{ \"delete\" : { \"_index\" : \""+index+"\", \"_type\" : \""+type+"\", \"_id\" : \""+id+"\" } }";
sb.append(str).append("\n");
System.out.println("delete "+sb.toString());
return sb.toString();
}
/**
* { "update" : {"_id" : "1", "_type" : "type1", "_index" : "test"} }
* { "doc" : {"field2" : "value2"} }
* @return
*/
private static String buildUpdate(JSONObject json,String index,String type,String id){
StringBuffer sb = new StringBuffer();
String str="{ \"update\" : { \"_index\" : \""+index+"\", \"_type\" : \""+type+"\", \"_id\" : \""+id+"\" } }";
sb.append(str).append("\n");
sb.append("{ \"doc\" : ").append(json).append("}").append("\n");
System.out.println("update: "+ sb.toString());
return sb.toString();
}
private static String buildInsert(JSONObject json,String index,String type,String id){
StringBuffer sb = new StringBuffer();
String str="{ \"index\" : { \"_index\" : \""+index+"\", \"_type\" : \""+type+"\", \"_id\" : \""+id+"\" } }";
sb.append(str).append("\n");
sb.append(json).append("\n");
System.out.println("insert: "+sb.toString());
return sb.toString();
}
public String postJson(String httpUrl, String json) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
StringEntity stringEntity = new StringEntity(json, "utf-8");// 解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
return sendHttpPost(httpPost);
}
private String sendHttpPost(HttpPost httpPost) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { httpClient = HttpClients.createDefault(); response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return responseContent; }