4 Commits 0456f427c6 ... c51b35fc27

Author SHA1 Message Date
  huangxy c51b35fc27 使用JEST实现ElasticSearch访问 6 years ago
  huangxy bd798f9499 elastic search api foundation 6 years ago
  huangxy 35d81a30eb http request pool 6 years ago
  huangxy 1b4ccc1e5d init 6 years ago

+ 25 - 10
.gitignore

@@ -1,14 +1,29 @@
-# ---> Java
-*.class
+/target/
+!.mvn/wrapper/maven-wrapper.jar
 
-# Mobile Tools for Java (J2ME)
-.mtj.tmp/
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
 
-# Package Files #
-*.jar
-*.war
-*.ear
+### IntelliJ IDEA ###
+/.idea/
+*.iws
+*.iml
+*.ipr
 
-# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
-hs_err_pid*
+### NetBeans ###
+/nbproject/private/
+/build/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
 
+mvnw
+mvnw.cmd
+/*/.mvn/

+ 12 - 0
README.md

@@ -1,2 +1,14 @@
 # study
 
+终身学习
+
+## study 项目
+
+## spring boot demo
+
+1. web api:jackson 接口返回 json数据
+2. http连接池,bean配置
+
+elastic search demo
+
+mybatis mysql

+ 85 - 0
study/pom.xml

@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.hxy</groupId>
+    <artifactId>study</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <packaging>jar</packaging>
+
+    <name>study</name>
+    <description>Demo project for Spring Boot</description>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.1.0.RELEASE</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+        <java.version>1.8</java.version>
+    </properties>
+
+    <dependencies>
+        <!--搜索引擎-->
+        <dependency>
+            <groupId>org.elasticsearch</groupId>
+            <artifactId>elasticsearch</artifactId>
+            <version>5.5.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>io.searchbox</groupId>
+            <artifactId>jest</artifactId>
+            <version>5.3.3</version>
+        </dependency>
+
+        <!--commons start-->
+        <!--通用辅助插件-->
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <version>3.8.1</version>
+        </dependency>
+
+        <!--http client-->
+        <dependency>
+            <groupId>commons-httpclient</groupId>
+            <artifactId>commons-httpclient</artifactId>
+            <version>3.1</version>
+        </dependency>
+        <!--commons stop-->
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-configuration-processor</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+
+</project>

+ 12 - 0
study/src/main/java/com/hxy/study/StudyApplication.java

@@ -0,0 +1,12 @@
+package com.hxy.study;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class StudyApplication {
+
+	public static void main(String[] args) {
+		SpringApplication.run(StudyApplication.class, args);
+	}
+}

+ 28 - 0
study/src/main/java/com/hxy/study/config/ElasticSearchConfig.java

@@ -0,0 +1,28 @@
+package com.hxy.study.config;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Component
+@ConfigurationProperties("elastic-search")
+public class ElasticSearchConfig {
+    private String serverIp;
+
+    private Integer serverPort;
+
+    public String getServerIp() {
+        return serverIp;
+    }
+
+    public void setServerIp(String serverIp) {
+        this.serverIp = serverIp;
+    }
+
+    public Integer getServerPort() {
+        return serverPort;
+    }
+
+    public void setServerPort(Integer serverPort) {
+        this.serverPort = serverPort;
+    }
+}

+ 38 - 0
study/src/main/java/com/hxy/study/config/MainConfig.java

@@ -0,0 +1,38 @@
+package com.hxy.study.config;
+
+import com.hxy.study.util.HttpClientHelper;
+import io.searchbox.client.JestClient;
+import io.searchbox.client.JestClientFactory;
+import io.searchbox.client.config.HttpClientConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.net.UnknownHostException;
+
+@Configuration
+public class MainConfig {
+    @Autowired
+    private ElasticSearchConfig elasticSearchConfig;
+
+    @Bean("httpClientHelper")
+    public HttpClientHelper httpClientHelper() {
+        return new HttpClientHelper();
+    }
+
+    @Bean
+    public JestClient client() throws UnknownHostException {
+        // Construct a new Jest client according to configuration via factory
+        JestClientFactory factory = new JestClientFactory();
+        factory.setHttpClientConfig(new HttpClientConfig
+                .Builder("http://" + elasticSearchConfig.getServerIp() + ":" + elasticSearchConfig.getServerPort())
+                .multiThreaded(true)
+                //Per default this implementation will create no more than 2 concurrent connections per given route
+                .defaultMaxTotalConnectionPerRoute(2)
+                // and no more 20 connections in total
+                .maxTotalConnection(20)
+                .build());
+        JestClient client = factory.getObject();
+        return client;
+    }
+}

+ 22 - 0
study/src/main/java/com/hxy/study/controller/Controller.java

@@ -0,0 +1,22 @@
+package com.hxy.study.controller;
+
+import com.hxy.study.controller.dto.Demo;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/")
+public class Controller {
+
+    @GetMapping("main")
+    public String main() {
+        return "Hello world!";
+    }
+
+    @GetMapping("demo")
+    public Demo demo() {
+        return new Demo("huangxiangyu", 18);
+    }
+
+}

+ 54 - 0
study/src/main/java/com/hxy/study/controller/dto/Account.java

@@ -0,0 +1,54 @@
+package com.hxy.study.controller.dto;
+
+public class Account {
+
+    private Long id;
+
+    private String user;
+
+    private String title;
+
+    private String desc;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getUser() {
+        return user;
+    }
+
+    public void setUser(String user) {
+        this.user = user;
+    }
+
+    public String getTitle() {
+        return title;
+    }
+
+    public void setTitle(String title) {
+        this.title = title;
+    }
+
+    public String getDesc() {
+        return desc;
+    }
+
+    public void setDesc(String desc) {
+        this.desc = desc;
+    }
+
+    @Override
+    public String toString() {
+        return "Account{" +
+                "id=" + id +
+                ", user='" + user + '\'' +
+                ", title='" + title + '\'' +
+                ", desc='" + desc + '\'' +
+                '}';
+    }
+}

+ 29 - 0
study/src/main/java/com/hxy/study/controller/dto/Demo.java

@@ -0,0 +1,29 @@
+package com.hxy.study.controller.dto;
+
+public class Demo {
+
+    private String name;
+
+    private Integer age;
+
+    public Demo(String name, Integer age) {
+        this.name = name;
+        this.age = age;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Integer getAge() {
+        return age;
+    }
+
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+}

+ 44 - 0
study/src/main/java/com/hxy/study/controller/dto/Paper.java

@@ -0,0 +1,44 @@
+package com.hxy.study.controller.dto;
+
+public class Paper {
+
+    private Long id;
+
+    private String name;
+
+    private String author;
+
+    private String type;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getAuthor() {
+        return author;
+    }
+
+    public void setAuthor(String author) {
+        this.author = author;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+}

+ 6 - 0
study/src/main/java/com/hxy/study/service/DemoService.java

@@ -0,0 +1,6 @@
+package com.hxy.study.service;
+
+public interface DemoService {
+
+    void httpGet();
+}

+ 5 - 0
study/src/main/java/com/hxy/study/service/SearchService.java

@@ -0,0 +1,5 @@
+package com.hxy.study.service;
+
+public interface SearchService {
+
+}

+ 39 - 0
study/src/main/java/com/hxy/study/service/impl/DemoServiceImpl.java

@@ -0,0 +1,39 @@
+package com.hxy.study.service.impl;
+
+import com.hxy.study.service.DemoService;
+import com.hxy.study.util.HttpClientHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+public class DemoServiceImpl implements DemoService {
+    private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
+
+    private final HttpClientHelper httpClientHelper;
+
+    @Autowired
+    public DemoServiceImpl(HttpClientHelper httpClientHelper) {
+        this.httpClientHelper = httpClientHelper;
+    }
+
+    @Override
+    public void httpGet() {
+        try {
+            Map<String, Object> param = new HashMap<>();
+            param.put("hiworkVersion", "v1.3");
+            param.put("evn", "v1");
+            int ss = httpClientHelper.get("https://smp.hoswork.com/api/miniapp/test/getversion", param, (httpstatus, httpMethod, cookies) -> {
+                logger.info("httpstatus:{}", httpstatus);
+                logger.info("response:{}", httpMethod.getResponseBodyAsString());
+            });
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 4 - 0
study/src/main/java/com/hxy/study/service/impl/SearchServiceImpl.java

@@ -0,0 +1,4 @@
+package com.hxy.study.service.impl;
+
+public class SearchServiceImpl {
+}

+ 20 - 0
study/src/main/java/com/hxy/study/util/HttpCallback.java

@@ -0,0 +1,20 @@
+package com.hxy.study.util;
+
+
+import org.apache.commons.httpclient.Cookie;
+import org.apache.commons.httpclient.HttpMethod;
+
+import java.io.IOException;
+
+public interface HttpCallback {
+
+    /**
+     * callback when get response. if you need headers, httpMethod.getResponseHeaders()
+     *
+     * @param httpMethod
+     * @param cookies
+     * @throws IOException
+     * @see HttpClientHelper
+     */
+    void callback(int httpstatus, HttpMethod httpMethod, Cookie[] cookies) throws IOException;
+}

+ 631 - 0
study/src/main/java/com/hxy/study/util/HttpClientHelper.java

@@ -0,0 +1,631 @@
+package com.hxy.study.util;
+
+
+import org.apache.commons.httpclient.*;
+import org.apache.commons.httpclient.methods.*;
+import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
+import org.apache.commons.httpclient.util.EncodingUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Array;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ *
+ * @author dengzhineng
+ * @date 2016年8月26日
+ */
+public class HttpClientHelper implements HttpHelper {
+
+    private static final Log logger = LogFactory.getLog(HttpClientHelper.class);
+    private static final String ENV_PROXY_KEY = "HTTP_PROXY";
+    private HttpClient client;
+    private MultiThreadedHttpConnectionManager manager;
+    private int connectionTimeout = 2000;
+    private int soTimeout = 5000;
+    private int maxTotalConnections = 4096;
+    private int defaultMaxConnectionsPerHost = 1024;
+
+    @Override
+    public void destroy() {
+        this.manager.shutdown();
+    }
+
+    /**
+     * @return the connectionTimeout
+     */
+    public int getConnectionTimeout() {
+        return this.connectionTimeout;
+    }
+
+    /**
+     * @param connectionTimeout the connectionTimeout to set
+     */
+    public void setConnectionTimeout(int connectionTimeout) {
+        this.connectionTimeout = connectionTimeout;
+        this.manager.getParams().setConnectionTimeout(connectionTimeout);
+    }
+
+    /**
+     * @return the soTimeout
+     */
+    public int getSoTimeout() {
+        return this.soTimeout;
+    }
+
+    /**
+     * @param soTimeout the soTimeout to set
+     */
+    public void setSoTimeout(int soTimeout) {
+        this.soTimeout = soTimeout;
+        this.manager.getParams().setSoTimeout(soTimeout);
+    }
+
+    /**
+     * @return the maxTotalConnections
+     */
+    public int getMaxTotalConnections() {
+        return this.maxTotalConnections;
+    }
+
+    /**
+     * @param maxTotalConnections the maxTotalConnections to set
+     */
+    public void setMaxTotalConnections(int maxTotalConnections) {
+        this.maxTotalConnections = maxTotalConnections;
+        this.manager.getParams().setMaxTotalConnections(maxTotalConnections);
+    }
+
+    /**
+     * @return the defaultMaxConnectionsPerHost
+     */
+    public int getDefaultMaxConnectionsPerHost() {
+        return this.defaultMaxConnectionsPerHost;
+    }
+
+    /**
+     * @param defaultMaxConnectionsPerHost the defaultMaxConnectionsPerHost to
+     *            set
+     */
+    public void setDefaultMaxConnectionsPerHost(int defaultMaxConnectionsPerHost) {
+        this.defaultMaxConnectionsPerHost = defaultMaxConnectionsPerHost;
+        this.manager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnectionsPerHost);
+    }
+
+    public HttpClientHelper(boolean initProxy) {
+        this();
+        if (initProxy) {
+            try {
+                // check is system properties include proxy info
+                String proxyHost = HttpClientHelper.trimToNull(System.getenv(HttpClientHelper.ENV_PROXY_KEY));
+                proxyHost = System.getProperty(HttpClientHelper.ENV_PROXY_KEY, proxyHost);
+                String proxyPort = null;
+                if (proxyHost != null) {
+                    int idx = proxyHost.indexOf(":");
+                    proxyPort = proxyHost.substring(idx + 1);
+                    proxyHost = proxyHost.substring(0, idx);
+                    this.setProxy(proxyHost, Integer.parseInt(proxyPort));
+                } else {
+                    HttpClientHelper.logger.warn("HttpClientHelper no proxy to set");
+                }
+            } catch (Exception e) {
+                HttpClientHelper.logger.warn("use proxy fail", e);
+            }
+        }
+    }
+
+    public HttpClientHelper(String proxyHost, int proxyPort) {
+        this();
+        this.setProxy(proxyHost, proxyPort);
+    }
+
+    public HttpClientHelper() {
+        this.manager = new MultiThreadedHttpConnectionManager();
+        HttpConnectionManagerParams paras = new HttpConnectionManagerParams();
+        paras.setConnectionTimeout(this.connectionTimeout);
+        paras.setSoTimeout(this.soTimeout);
+        paras.setMaxTotalConnections(this.maxTotalConnections);
+        paras.setDefaultMaxConnectionsPerHost(this.defaultMaxConnectionsPerHost);
+        this.manager.setParams(paras);
+        this.client = new HttpClient(this.manager);
+    }
+
+    private void setProxy(String proxyHost, int port) {
+        proxyHost = HttpClientHelper.trimToNull(proxyHost);
+        if (proxyHost != null) {
+            this.client.getHostConfiguration().setProxy(proxyHost, port);
+        }
+    }
+
+    @Override
+    public int exec(HttpMethod method, HttpState httpState, HttpCallback callback) throws IOException {
+        try {
+            if (httpState == null) {
+                httpState = new HttpState();
+            }
+            int r = this.client.executeMethod(null, method, httpState);
+            if (callback != null) {
+                callback.callback(r, method, httpState.getCookies());
+            }
+            return r;
+        } finally {
+            if (method != null) {
+                method.releaseConnection();
+            }
+        }
+    }
+
+    protected HttpState setHttpState(HttpState httpState, Map<String, String> cookies, String url) throws IOException {
+        if (httpState == null) {
+            httpState = new HttpState();
+        }
+        if (cookies != null && cookies.size() != 0) {
+            String n;
+            String host = this.getHost(url);
+            for (Entry<String, String> en : cookies.entrySet()) {
+                n = HttpClientHelper.trimToNull(en.getKey());
+                if (n != null) {
+                    httpState.addCookie(new Cookie(host, n, en.getValue(), "/", null, false));
+                }
+            }
+        }
+        return httpState;
+    }
+
+    protected String getHost(String url) throws MalformedURLException {
+        return new URL(url).getHost();
+    }
+
+    protected HttpState setHttpState(HttpState httpState, Cookie[] cookies, String url) throws IOException {
+        if (httpState == null) {
+            httpState = new HttpState();
+        }
+        if (cookies != null && cookies.length > 0) {
+            String host = this.getHost(url);
+            for (Cookie c : cookies) {
+                if (c != null) {
+                    if (c.getDomain() == null) {
+                        c.setDomain(host);
+                    }
+                    if (c.getPath() == null) {
+                        c.setPath("/");
+                    }
+                    httpState.addCookie(c);
+                }
+            }
+        }
+        return httpState;
+    }
+
+    protected <T> HttpMethod getGetMethod(String uri, Map<String, T> data, String charset, Header[] headers) {
+        return this.setParameter(this.getGetMethod(uri, charset, headers), data, charset);
+    }
+
+    protected <T> HttpMethod getGetMethod(String uri, String queryStr, String charset, Header[] headers) {
+        return this.setParameter(this.getGetMethod(uri, charset, headers), queryStr);
+    }
+
+    protected <T> HttpMethod getGetMethod(String uri, Map<String, T> data, String charset, Map<String, String> headers) {
+        return this.getGetMethod(uri, data, charset, this.createHeaders(headers));
+    }
+
+    protected GetMethod getGetMethod(String uri, String charset, Header[] headers) {
+        GetMethod getMethod = new GetMethod(uri);
+        getMethod.setFollowRedirects(true);
+        if (charset == null) {
+            charset = HttpHelper.DEFAULT_CHARSET;
+        }
+        getMethod.getParams().setContentCharset(charset);
+        if (headers != null && headers.length != 0) {
+            for (Header h : headers) {
+                if (h != null) {
+                    getMethod.addRequestHeader(h);
+                }
+            }
+        }
+        return getMethod;
+    }
+
+    protected <T> GetMethod setParameter(GetMethod getMethod, Map<String, T> data, String charset) {
+        if (charset == null) {
+            charset = HttpHelper.DEFAULT_CHARSET;
+        }
+        if (data != null && data.size() != 0) {
+            List<NameValuePair> paras = new ArrayList<NameValuePair>(data.size());
+            for (Entry<String, T> entry : data.entrySet()) {
+                Object value = entry.getValue();
+                if (value != null) {
+                    if (value instanceof String) {
+                        paras.add(new NameValuePair(entry.getKey(), (String) value));
+                    } else if (value instanceof Iterable) {
+                        for (Object v : ((Iterable<?>) value)) {
+                            if (v != null) {
+                                paras.add(new NameValuePair(entry.getKey(), String.valueOf(v)));
+                            }
+                        }
+                    } else if (value.getClass().isArray()) {
+                        int len = Array.getLength(value);
+                        for (int i = 0; i < len; i++) {
+                            Object v = Array.get(value, i);
+                            if (v != null) {
+                                paras.add(new NameValuePair(entry.getKey(), String.valueOf(v)));
+                            }
+                        }
+                    } else {
+                        paras.add(new NameValuePair(entry.getKey(), String.valueOf(value)));
+                    }
+                }
+            }
+            if (paras.size() != 0) {
+                String qStr = HttpClientHelper.trimToNull(getMethod.getQueryString());
+                if (qStr != null) {
+                    getMethod.setQueryString(
+                            qStr + "&" + EncodingUtil.formUrlEncode(paras.toArray(new NameValuePair[paras.size()]), charset));
+                } else {
+                    getMethod.setQueryString(EncodingUtil.formUrlEncode(paras.toArray(new NameValuePair[paras.size()]), charset));
+                }
+            }
+        }
+        return getMethod;
+    }
+
+    protected <T> GetMethod setParameter(GetMethod getMethod, String queryStr) {
+        if (StringUtils.isBlank(queryStr)) {
+            return getMethod;
+        }
+        String qStr = HttpClientHelper.trimToNull(getMethod.getQueryString());
+        if (qStr != null) {
+            getMethod.setQueryString(qStr + "&" + queryStr);
+        } else {
+            getMethod.setQueryString(queryStr);
+        }
+        return getMethod;
+    }
+
+    public static String trimToNull(String str) {
+        if (str != null) {
+            str = str.trim();
+        }
+        return (str == null || str.length() == 0) ? null : str;
+    }
+
+    protected Header[] createHeaders(Map<String, String> headers) {
+        if (headers != null && headers.size() != 0) {
+            List<Header> hs = new ArrayList<Header>(headers.size());
+            for (Entry<String, String> en : headers.entrySet()) {
+                hs.add(new Header(en.getKey(), en.getValue()));
+            }
+            return hs.toArray(new Header[hs.size()]);
+        }
+        return null;
+    }
+
+    protected HttpMethod getPostMethod(String uri, String charset, Map<String, String> headers, InputStream data) {
+        return this.getPostMethod(uri, charset, this.createHeaders(headers), data);
+    }
+
+    protected HttpMethod getPostMethod(String uri, String charset, Header[] headers, InputStream data) {
+        return this.setParameter(this.getPostMethod(uri, charset, headers, "application/octet-stream"), data);
+    }
+
+    protected <T> HttpMethod getPostMethod(String uri, String charset, Header[] headers, Map<String, T> data) {
+        return this.setParameter(this.getPostMethod(uri, charset, headers, HttpClientHelper.DEFAULT_POST_CONTENT_TYPE), data);
+    }
+
+    protected <T> HttpMethod getPostMethod(String uri, String charset, Map<String, String> headers, Map<String, T> data) {
+        return this.getPostMethod(uri, charset, this.createHeaders(headers), data);
+    }
+
+    protected PostMethod getPostMethod(String uri, String charset, Header[] headers, String contentType) {
+        PostMethod postMethod = new PostMethod(uri);
+        if (charset == null) {
+            charset = HttpHelper.DEFAULT_CHARSET;
+        }
+        postMethod.getParams().setContentCharset(charset);
+        boolean ct = false;
+        if (headers != null && headers.length != 0) {
+            for (Header h : headers) {
+                ct = ct || HttpHelper.HEADER_NAME_CONTENT_TYPE.equalsIgnoreCase(h.getName());
+                postMethod.addRequestHeader(h);
+            }
+        }
+        if (!ct) {
+            postMethod.addRequestHeader(HttpHelper.HEADER_NAME_CONTENT_TYPE, contentType);
+        }
+        return postMethod;
+    }
+
+    protected PostMethod setParameter(PostMethod postMethod, InputStream data) {
+        if (data != null) {
+            postMethod.setRequestEntity(new InputStreamRequestEntity(data));
+        }
+        return postMethod;
+    }
+
+    protected <T> PostMethod setParameter(PostMethod postMethod, Map<String, T> data) {
+        if (data != null && data.size() > 0) {
+            for (Entry<String, T> entry : data.entrySet()) {
+                Object value = entry.getValue();
+                if (value != null) {
+                    if (value instanceof String) {
+                        postMethod.addParameter(entry.getKey(), (String) value);
+                    } else if (value instanceof Iterable) {
+                        for (Object v : ((Iterable<?>) value)) {
+                            if (v != null) {
+                                postMethod.addParameter(entry.getKey(), String.valueOf(v));
+                            }
+                        }
+                    } else if (value.getClass().isArray()) {
+                        int len = Array.getLength(value);
+                        for (int i = 0; i < len; i++) {
+                            Object v = Array.get(value, i);
+                            if (v != null) {
+                                postMethod.addParameter(entry.getKey(), String.valueOf(v));
+                            }
+                        }
+                    } else {
+                        postMethod.addParameter(entry.getKey(), String.valueOf(value));
+                    }
+                }
+            }
+        }
+        return postMethod;
+    }
+
+    public final static String DEFAULT_POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
+
+    @Override
+    public <T> int get(String address, Map<String, T> data) throws IOException {
+        return this.get(address, data, null);
+    }
+
+    @Override
+    public <T> int get(String address, Map<String, T> data, HttpCallback callback) throws IOException {
+        return this.get(address, data, HttpHelper.DEFAULT_CHARSET, (Cookie[]) null, (Header[]) null, callback);
+    }
+
+    @Override
+    public <T> int get(String address, Map<String, T> data, String charset, Cookie[] cookies, Header[] headers,
+            HttpCallback callback) throws IOException {
+        return this.exec(this.getGetMethod(address, data, charset, headers), this.setHttpState(null, cookies, address), callback);
+    }
+
+    @Override
+    public <T> int get(String address, Map<String, T> data, String charset, Map<String, String> cookies,
+            Map<String, String> headers, HttpCallback callback) throws IOException {
+        return this.exec(this.getGetMethod(address, data, charset, headers), this.setHttpState(null, cookies, address), callback);
+    }
+
+    @Override
+    public <T> int get(String address, String queryStr, String charset, Map<String, String> cookies, Header[] headers,
+            HttpCallback callback) throws IOException {
+        return this.exec(this.getGetMethod(address, queryStr, charset, headers), this.setHttpState(null, cookies, address),
+                callback);
+    }
+
+    @Override
+    public <T> int post(String address, Map<String, T> data) throws IOException {
+        return this.post(address, data, null);
+    }
+
+    @Override
+    public <T> int post(String address, Map<String, T> data, HttpCallback callback) throws IOException {
+        return this.post(address, data, HttpHelper.DEFAULT_CHARSET, (Cookie[]) null, (Header[]) null, callback);
+    }
+
+    @Override
+    public <T> int post(String address, Map<String, T> data, String charset, Map<String, String> cookies,
+            Map<String, String> headers, HttpCallback callback) throws IOException {
+        return this.exec(this.getPostMethod(address, charset, headers, data), this.setHttpState(null, cookies, address),
+                callback);
+    }
+
+    @Override
+    public <T> int post(String address, Map<String, T> data, String charset, Cookie[] cookies, Header[] headers,
+            HttpCallback callback) throws IOException {
+        return this.exec(this.getPostMethod(address, charset, headers, data), this.setHttpState(null, cookies, address),
+                callback);
+    }
+
+    @Override
+    public int post(String address, InputStream data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException {
+        return this.exec(this.getPostMethod(address, charset, headers, data), this.setHttpState(null, cookies, address),
+                callback);
+    }
+
+    @Override
+    public int post(String address, InputStream data, String charset, Map<String, String> cookies, Map<String, String> headers,
+            HttpCallback callback) throws IOException {
+        return this.exec(this.getPostMethod(address, charset, headers, data), this.setHttpState(null, cookies, address),
+                callback);
+    }
+
+    @Override
+    public int post(String address, byte[] data, String charset, Map<String, String> cookies, Header[] headers,
+            HttpCallback callback) throws IOException {
+        return this.exec(this.getPostMethod(address, charset, headers, new ByteArrayInputStream(data)),
+                this.setHttpState(null, cookies, address), callback);
+    }
+
+    @Override
+    public int post(String address, String data, String charset, String contentType, HttpCallback callback) throws IOException {
+        Header[] headers = new Header[1];
+        if (StringUtils.isNotBlank(contentType)) {
+            headers[0] = new Header(HttpHelper.HEADER_NAME_CONTENT_TYPE, contentType);
+        } else {
+            headers[0] = new Header(HttpHelper.HEADER_NAME_CONTENT_TYPE, "text/plain");
+        }
+        return post(address, getBytes(data, charset), charset, null, headers, callback);
+    }
+
+    protected byte[] getBytes(String data, String charset) throws UnsupportedEncodingException {
+        if (data == null) {
+            return new byte[0];
+        }
+        if (charset == null) {
+            charset = HttpHelper.DEFAULT_CHARSET;
+        }
+        return data.getBytes(charset);
+    }
+
+    @Override
+    public <T> int put(String address, Map<String, T> data) throws IOException {
+        return this.put(address, data, null);
+    }
+
+    @Override
+    public <T> int put(String address, Map<String, T> data, HttpCallback callback) throws IOException {
+        return this.put(address, data, HttpHelper.DEFAULT_CHARSET, (Cookie[]) null, (Header[]) null, callback);
+    }
+
+    @Override
+    public <T> int put(String address, Map<String, T> data, String charset, Cookie[] cookies, Header[] headers,
+            HttpCallback callback) throws IOException {
+        return this.exec(this.getPutMethod(address, charset, headers, data), this.setHttpState(null, cookies, address), callback);
+    }
+
+    @Override
+    public int put(String address, InputStream data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException {
+        return this.exec(this.getPutMethod(address, charset, headers, data), this.setHttpState(null, cookies, address), callback);
+    }
+
+    @Override
+    public int put(String address, byte[] data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException {
+        return this.exec(this.getPutMethod(address, charset, headers, data), this.setHttpState(null, cookies, address), callback);
+    }
+
+    @Override
+    public int put(String address, String data, String charset, String contentType, HttpCallback callback) throws IOException {
+        Header[] headers = new Header[1];
+        if (StringUtils.isNotBlank(contentType)) {
+            headers[0] = new Header(HttpHelper.HEADER_NAME_CONTENT_TYPE, contentType);
+        } else {
+            headers[0] = new Header(HttpHelper.HEADER_NAME_CONTENT_TYPE, "text/plain");
+        }
+        return this.exec(this.getPutMethod(address, charset, headers, contentType, data),
+                this.setHttpState(null, (Cookie[]) null, address), callback);
+    }
+
+    protected HttpMethod getPutMethod(String uri, String charset, Header[] headers, InputStream data) {
+        return this.setEntity(this.getPutMethod(uri, charset, headers, "application/octet-stream"), data);
+    }
+
+    protected <T> HttpMethod getPutMethod(String uri, String charset, Header[] headers, Map<String, T> data)
+            throws UnsupportedEncodingException {
+        return this.setEntity(this.getPutMethod(uri, charset, headers, HttpClientHelper.DEFAULT_POST_CONTENT_TYPE), data,
+                charset);
+    }
+
+    protected HttpMethod getPutMethod(String uri, String charset, Header[] headers, byte[] data)
+            throws UnsupportedEncodingException {
+        return this.setEntity(this.getPutMethod(uri, charset, headers, HttpClientHelper.DEFAULT_POST_CONTENT_TYPE), data);
+    }
+
+    protected HttpMethod getPutMethod(String uri, String charset, Header[] headers, String contentType, String data)
+            throws UnsupportedEncodingException {
+        return this.setEntity(this.getPutMethod(uri, charset, headers, contentType), data, contentType, charset);
+    }
+
+    protected PutMethod getPutMethod(String uri, String charset, Header[] headers, String contentType) {
+        PutMethod putMethod = new PutMethod(uri);
+        if (charset == null) {
+            charset = HttpHelper.DEFAULT_CHARSET;
+        }
+        putMethod.getParams().setContentCharset(charset);
+        boolean ct = false;
+        if (headers != null && headers.length != 0) {
+            for (Header h : headers) {
+                ct = ct || HttpHelper.HEADER_NAME_CONTENT_TYPE.equalsIgnoreCase(h.getName());
+                putMethod.addRequestHeader(h);
+            }
+        }
+        if (!ct) {
+            putMethod.addRequestHeader(HttpHelper.HEADER_NAME_CONTENT_TYPE, contentType);
+        }
+        return putMethod;
+    }
+
+    protected PutMethod setEntity(PutMethod putMethod, InputStream data) {
+        if (data != null) {
+            putMethod.setRequestEntity(new InputStreamRequestEntity(data));
+        }
+        return putMethod;
+    }
+
+    protected PutMethod setEntity(PutMethod putMethod, byte[] data) {
+        if (data != null) {
+            putMethod.setRequestEntity(new ByteArrayRequestEntity(data));
+        }
+        return putMethod;
+    }
+
+    protected PutMethod setEntity(PutMethod putMethod, String data, String contentType, String charset)
+            throws UnsupportedEncodingException {
+        if (data != null) {
+            putMethod.setRequestEntity(new StringRequestEntity(data, contentType, charset));
+        }
+        return putMethod;
+    }
+
+    protected <T> PutMethod setEntity(PutMethod putMethod, Map<String, T> data, String charset)
+            throws UnsupportedEncodingException {
+        if (data != null && data.size() > 0) {
+            StringBuilder builder = new StringBuilder();
+            for (Entry<String, T> entry : data.entrySet()) {
+                Object value = entry.getValue();
+                if (value != null) {
+                    if (value instanceof String) {
+                        builder.append(URLEncoder.encode(entry.getKey(), charset)).append("=")
+                                .append(URLEncoder.encode((String) value, charset)).append("&");
+                    } else if (value instanceof Iterable) {
+                        builder.append(URLEncoder.encode(entry.getKey(), charset)).append("=");
+                        StringBuilder temp = new StringBuilder();
+                        for (Object v : ((Iterable<?>) value)) {
+                            if (v != null) {
+                                temp.append(String.valueOf(v)).append(",");
+                            }
+                        }
+                        if (',' == temp.charAt(temp.length() - 1)) {
+                            temp.deleteCharAt(temp.length() - 1);
+                        }
+                        builder.append(URLEncoder.encode(temp.toString(), charset)).append("&");
+                    } else if (value.getClass().isArray()) {
+                        builder.append(URLEncoder.encode(entry.getKey(), charset)).append("=");
+                        StringBuilder temp = new StringBuilder();
+                        int len = Array.getLength(value);
+                        for (int i = 0; i < len; i++) {
+                            Object v = Array.get(value, i);
+                            if (v != null) {
+                                temp.append(String.valueOf(v)).append(",");
+                            }
+                        }
+                        if (',' == temp.charAt(temp.length() - 1)) {
+                            temp.deleteCharAt(temp.length() - 1);
+                        }
+                        builder.append(URLEncoder.encode(temp.toString(), charset)).append("&");
+                    } else {
+                        builder.append(URLEncoder.encode(entry.getKey(), charset)).append("=")
+                                .append(URLEncoder.encode(String.valueOf(value), charset)).append("&");
+                    }
+                }
+            }
+        }
+        return putMethod;
+    }
+
+}

+ 76 - 0
study/src/main/java/com/hxy/study/util/HttpHelper.java

@@ -0,0 +1,76 @@
+package com.hxy.study.util;
+
+import org.apache.commons.httpclient.Cookie;
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpState;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+
+/**
+ *
+ * @author dengzhineng
+ * @date 2016年8月26日
+ */
+public interface HttpHelper {
+
+    public static final String HEADER_NAME_CONTENT_TYPE = "Content-Type";
+
+    public static final String DEFAULT_CHARSET = "UTF-8";
+
+    <T> int get(String address, Map<String, T> data) throws IOException;
+
+    <T> int get(String address, Map<String, T> data, HttpCallback callback) throws IOException;
+
+    <T> int get(String address, Map<String, T> data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    <T> int get(String address, Map<String, T> data, String charset, Map<String, String> cookies, Map<String, String> headers,
+            HttpCallback callback) throws IOException;
+
+    <T> int get(String address, String queryStr, String charset, Map<String, String> cookies, Header[] headers,
+            HttpCallback callback) throws IOException;
+
+    <T> int post(String address, Map<String, T> data) throws IOException;
+
+    <T> int post(String address, Map<String, T> data, HttpCallback callback) throws IOException;
+
+    <T> int post(String address, Map<String, T> data, String charset, Map<String, String> cookies, Map<String, String> headers,
+            HttpCallback callback) throws IOException;
+
+    <T> int post(String address, Map<String, T> data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    int post(String address, InputStream data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    int post(String address, InputStream data, String charset, Map<String, String> cookies, Map<String, String> headers,
+            HttpCallback callback) throws IOException;
+
+    int exec(HttpMethod method, HttpState httpState, HttpCallback callback) throws IOException;
+
+    int post(String address, byte[] data, String charset, Map<String, String> cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    int post(String address, String data, String charset, String contentType, HttpCallback callback) throws IOException;
+
+    void destroy();
+
+    <T> int put(String address, Map<String, T> data) throws IOException;
+
+    <T> int put(String address, Map<String, T> data, HttpCallback callback) throws IOException;
+
+    <T> int put(String address, Map<String, T> data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    int put(String address, InputStream data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    int put(String address, byte[] data, String charset, Cookie[] cookies, Header[] headers, HttpCallback callback)
+            throws IOException;
+
+    int put(String address, String data, String charset, String contentType, HttpCallback callback) throws IOException;
+
+}

+ 0 - 0
study/src/main/resources/application.properties


+ 3 - 0
study/src/main/resources/application.yaml

@@ -0,0 +1,3 @@
+elastic-search:
+  serverIp: 192.168.232.157
+  serverPort: 9200

+ 21 - 0
study/src/test/java/com/hxy/study/DemoServiceTest.java

@@ -0,0 +1,21 @@
+package com.hxy.study;
+
+import com.hxy.study.service.DemoService;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class DemoServiceTest {
+
+    @Autowired
+    private DemoService demoService;
+
+    @Test
+    public void test(){
+        demoService.httpGet();
+    }
+}

+ 102 - 0
study/src/test/java/com/hxy/study/SearchClientTest.java

@@ -0,0 +1,102 @@
+package com.hxy.study;
+
+import com.hxy.study.config.ElasticSearchConfig;
+import com.hxy.study.util.HttpClientHelper;
+import io.searchbox.client.JestClient;
+import io.searchbox.core.Search;
+import io.searchbox.core.SearchResult;
+import org.elasticsearch.index.query.QueryBuilder;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.Map;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class SearchClientTest {
+
+    @Autowired
+    private ElasticSearchConfig elasticSearchConfig;
+
+    @Autowired
+    private HttpClientHelper httpClientHelper;
+
+    @Autowired
+    private JestClient jestClient;
+
+    @Test
+    public void getInterAddress() {
+        try {
+            InetAddress inetAddress = InetAddress.getByName(elasticSearchConfig.getServerIp());
+            System.out.println();
+        } catch (UnknownHostException e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 使用Jest 利用 Http res接口访问 ElasticSearch
+     * 查询条件用的是ElasticSearch官方提供的类
+     */
+    @Test
+    public void testJestEs() {
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        QueryBuilder queryBuilder = QueryBuilders
+                .matchQuery("name", "英语试题");//单值完全匹配查询
+        QueryBuilder queryBuilderAuthor = QueryBuilders.matchQuery("author", "马");
+        QueryBuilder allClause = QueryBuilders.boolQuery().should(queryBuilder).should(queryBuilderAuthor);
+        searchSourceBuilder.query(allClause);
+        searchSourceBuilder.size(10);
+        searchSourceBuilder.from(0);
+
+        String query = searchSourceBuilder.toString();
+        System.out.println(query);
+        Search search = new Search.Builder(query)
+                .addIndex("t_paper")
+                .build();
+        try {
+            SearchResult result = jestClient.execute(search);
+            System.out.println(result.getJsonString());
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+        // other examples
+//        QueryBuilder levelClause = QueryBuilders.termsQuery("loglevel.keyword", "ERROR", "FATAL");
+//        QueryBuilder timeClause = QueryBuilders.rangeQuery("logtime.keyword").from(startTime).to(endTime);
+//        QueryBuilder queryBuilder = QueryBuilders.matchQuery("logclass.keyword", "com.huohuo.Test");
+        // and/or/not等:涉及到多条件查询用boolQuery,组合多个query。must表示and,mustNot表示not,should表示or。
+
+
+    }
+
+
+    @Test
+    public void restSearchTest() {
+        String url = "http://192.168.232.157:9200/accounts/person/_search";
+        Map<String, Object> data = new HashMap<>();
+
+        Map<String, Object> match = new HashMap<>();
+        match.put("desc", "软件 系统");
+
+        data.put("query", match);
+        try {
+            httpClientHelper.get(url, null, (httpstatus, httpMethod, cookies) -> {
+                System.out.println(httpstatus);
+                System.out.println(httpMethod.getResponseBodyAsString());
+            });
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 16 - 0
study/src/test/java/com/hxy/study/StudyApplicationTests.java

@@ -0,0 +1,16 @@
+package com.hxy.study;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class StudyApplicationTests {
+
+	@Test
+	public void contextLoads() {
+	}
+
+}