Browse Source

增加httpClient封装,准备替换hos-core中多个http封装的问题

Airhead 8 years ago
parent
commit
5e64050b55

+ 51 - 0
hos-http/pom.xml

@ -0,0 +1,51 @@
<?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.yihu.hos</groupId>
    <artifactId>hos-http</artifactId>
    <version>1.0-SNAPSHOT</version>
    <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>
        <!--httpclient start-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--httpclient end-->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

+ 15 - 0
hos-http/src/main/java/com/yihu/hos/http/AllowAllHostnameVerifier.java

@ -0,0 +1,15 @@
package com.yihu.hos.http;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
/**
 * @author Air
 * @version 1.0
 * @created 2015.07.02 15:48
 */
public class AllowAllHostnameVerifier implements HostnameVerifier {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

+ 46 - 0
hos-http/src/main/java/com/yihu/hos/http/HTTPClient.java

@ -0,0 +1,46 @@
package com.yihu.hos.http;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public interface HTTPClient {
    //主要的几种方法,其他的暂时未使用
    String GET = "GET";
    String POST = "POST";
    String PUT = "PUT";
    String DELETE = "DELETE";
    HTTPResponse get(String url);
    HTTPResponse get(String url, Map<String, String> params);
    HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse post(String url);
    HTTPResponse post(String url, Map<String, String> params);
    HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse postFile(String url, String path);
    HTTPResponse postFile(String url, String path, Map<String, String> params);
    HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers);
    HTTPResponse put(String url);
    HTTPResponse put(String url, Map<String, String> params);
    HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse delete(String url);
    HTTPResponse delete(String url, Map<String, String> params);
    HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers);
}

+ 299 - 0
hos-http/src/main/java/com/yihu/hos/http/HTTPClientDefaultImpl.java

@ -0,0 +1,299 @@
package com.yihu.hos.http;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public class HTTPClientDefaultImpl implements HTTPClient {
    private static final Log log = LogFactory.getLog(HTTPClientDefaultImpl.class);
    protected CloseableHttpClient httpClient;
    protected HttpClientContext httpClientContext;
    HTTPClientDefaultImpl(CloseableHttpClient httpClient, CredentialsProvider credentialsProvider) {
        this.httpClient = httpClient;
        if (credentialsProvider != null) {
            this.httpClientContext = HttpClientContext.create();
            httpClientContext.setCredentialsProvider(credentialsProvider);
        }
    }
    public HTTPResponse get(String url) {
        return get(url, null);
    }
    public HTTPResponse get(String url, Map<String, String> params) {
        return get(url, params, null);
    }
    public HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpResponse response;
        HttpEntity entity = null;
        try {
            HttpGet httpGet = new HttpGet(formatURL(url, params));
            authenticate(url, httpClientContext);
            addHeads(httpGet, headers);
            response = httpClient.execute(httpGet, httpClientContext);
            entity = response.getEntity();
            return new HTTPResponse(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
        return new HTTPResponse(500, "");
    }
    public HTTPResponse post(String url) {
        return post(url, null);
    }
    public HTTPResponse post(String url, Map<String, String> params) {
        return post(url, params, null);
    }
    public HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpResponse response;
        HttpEntity entity = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            authenticate(url, httpClientContext);
            addHeads(httpPost, headers);
            setEntity(httpPost, params);
            response = httpClient.execute(httpPost, httpClientContext);
            entity = response.getEntity();
            return new HTTPResponse(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
        return new HTTPResponse(500, "");
    }
    public HTTPResponse postFile(String url, String path) {
        return postFile(url, path, null);
    }
    public HTTPResponse postFile(String url, String path, Map<String, String> params) {
        return postFile(url, path, params, null);
    }
    public HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpResponse response;
        HttpEntity entity = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            authenticate(url, httpClientContext);
            addHeads(httpPost, headers);
            File file = new File(path);
            FileEntity fileEntity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));
            httpPost.setEntity(fileEntity);
            response = httpClient.execute(httpPost, httpClientContext);
            entity = response.getEntity();
            return new HTTPResponse(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
        return new HTTPResponse(500, "");
    }
    public HTTPResponse put(String url) {
        return put(url, null);
    }
    public HTTPResponse put(String url, Map<String, String> params) {
        return put(url, params, null);
    }
    public HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpResponse response;
        HttpEntity entity = null;
        try {
            HttpPut httpPut = new HttpPut(url);
            authenticate(url, httpClientContext);
            addHeads(httpPut, headers);
            setEntity(httpPut, params);
            response = httpClient.execute(httpPut, httpClientContext);
            entity = response.getEntity();
            return new HTTPResponse(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
        return new HTTPResponse(500, "");
    }
    public HTTPResponse delete(String url) {
        return delete(url, null);
    }
    public HTTPResponse delete(String url, Map<String, String> params) {
        return delete(url, params, null);
    }
    public HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpResponse response;
        HttpEntity entity = null;
        try {
            HttpDelete httpDelete = new HttpDelete(formatURL(url, params));
            authenticate(url, httpClientContext);
            addHeads(httpDelete, headers);
            response = httpClient.execute(httpDelete, httpClientContext);
            entity = response.getEntity();
            return new HTTPResponse(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
        return new HTTPResponse(500, "");
    }
    public HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers) {
        if (method.equals(POST)) {
            return post(url, params, headers);
        }
        if (method.equals(GET)) {
            return get(url, params, headers);
        }
        if (method.equals(PUT)) {
            return put(url, params, headers);
        }
        if (method.equals(DELETE)) {
            return delete(url, params, headers);
        }
        return get(url, params, headers);
    }
    private void addHeads(HttpRequestBase httpRequestBase, Map<String, String> headers) {
        if (headers == null) {
            return;
        }
        headers.forEach(httpRequestBase::addHeader);
    }
    private String formatURL(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }
        
        final String[] query = {""};
        params.forEach((name, value) -> {
            try {
                query[0] += "&" + name + URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("encode url ");
            }
        });
        if (url.contains("?")) {
            return url + query[0];
        }
        return url + "?" + query[0].substring(1);
    }
    private void authenticate(String url, HttpClientContext httpClientContext) throws MalformedURLException {
        URL r = new URL(url);
        String userInfo = r.getUserInfo();
        if (userInfo == null) {
            return;
        }
        String[] user = userInfo.split(":");
        String host = r.getHost();
        int port = r.getPort();
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(host, port),
                new org.apache.http.auth.UsernamePasswordCredentials(user[0], user[1]));
        if (httpClientContext == null) {
            httpClientContext = HttpClientContext.create();
        }
        httpClientContext.setCredentialsProvider(credentialsProvider);
    }
    private void setEntity(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, Map<String, String> params) {
        if (params == null) {
            return;
        }
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        params.forEach((name, value) -> nameValuePairs.add(new BasicNameValuePair(name, value)));
        UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8);
        httpEntityEnclosingRequestBase.setEntity(postEntity);
    }
}

+ 17 - 0
hos-http/src/main/java/com/yihu/hos/http/HTTPClientImpl.java

@ -0,0 +1,17 @@
package com.yihu.hos.http;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.HttpClients;
/**
 * @created Airhead 2016/8/24.
 */
public class HTTPClientImpl extends HTTPClientDefaultImpl {
    HTTPClientImpl() {
        super(HttpClients.createDefault(), null);
    }
    HTTPClientImpl(CredentialsProvider credentialsProvider){
        super(HttpClients.createDefault(), credentialsProvider);
    }
}

+ 19 - 0
hos-http/src/main/java/com/yihu/hos/http/HTTPResponse.java

@ -0,0 +1,19 @@
package com.yihu.hos.http;
/**
 * @created Airhead 2016/8/24.
 */
public class HTTPResponse {
    public final int statusCode;// e.g. 200
    public final String body;
    public HTTPResponse(int statusCode, String body) {
        this.statusCode = statusCode;
        this.body = body;
    }
//    public final String status; // e.g. "200 OK"
//    public final String proto; // e.g. "HTTP/1.0"
//    public final int protoMajor;     // e.g. 1
//    public final int protoMinor;    // e.g. 0
}

+ 22 - 0
hos-http/src/main/java/com/yihu/hos/http/HTTPSClientImpl.java

@ -0,0 +1,22 @@
package com.yihu.hos.http;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
/**
 * @created Airhead 2016/8/24.
 */
public class HTTPSClientImpl extends HTTPClientDefaultImpl {
    HTTPSClientImpl(SSLConnectionSocketFactory sslConnectionSocketFactory) {
        super(HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build(), null);
    }
    HTTPSClientImpl(SSLConnectionSocketFactory sslConnectionSocketFactory, CredentialsProvider credentialsProvider) {
        super(HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build(), credentialsProvider);
    }
}

+ 173 - 0
hos-http/src/main/java/com/yihu/hos/http/HttpClientKit.java

@ -0,0 +1,173 @@
package com.yihu.hos.http;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public class HttpClientKit {
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static Map<String, SSLConnectionSocketFactory> sslConnectionSocketFactoryMap = new HashMap<>();
    private static Map<String, CredentialsProvider> credentialsProviderMap = new HashMap<>();
    public static HTTPClient use(String url) {
        try {
            URL urlUse = new URL(url);
            String protocol = urlUse.getProtocol();
            String host = urlUse.getHost();
            int port = urlUse.getPort();
            if (protocol.equals(HTTPS)) {
                return getHttpsClient(host, port);
            } else if (protocol.equals(HTTP)) {
                return getHttpClient(host, port);
            }
        } catch (MalformedURLException ignored) {
        }
        return new HTTPClientImpl();
    }
    private static HTTPClient getHttpClient(String host, Integer port) {
        String key = host + ":" + port;
        CredentialsProvider credentialsProvider = credentialsProviderMap.get(key);
        if (credentialsProvider == null) {
            return new HTTPClientImpl();
        }
        return new HTTPClientImpl(credentialsProvider);
    }
    private static HTTPClient getHttpsClient(String host, Integer port) {
        String key = host + ":" + port;
        SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryMap.get(key);
        if (sslConnectionSocketFactory == null) {
            throw new IllegalArgumentException("must add trust store first.");
        }
        CredentialsProvider credentialsProvider = credentialsProviderMap.get(key);
        if (credentialsProvider == null) {
            return new HTTPSClientImpl(sslConnectionSocketFactory);
        }
        return new HTTPSClientImpl(sslConnectionSocketFactory, credentialsProvider);
    }
    public static void addTrustStore(String host, Integer port, String trustStorePath, String password) throws Exception {
        if (host == null || port == null || trustStorePath == null || password == null) {
            throw new IllegalArgumentException("must init basic credential first.");
        }
        SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryMap.get(host);
        if (sslConnectionSocketFactory != null) {
            return;
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new File(trustStorePath), password.toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();
        // Allow TLSv1 protocol only
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                new AllowAllHostnameVerifier());
        sslConnectionSocketFactoryMap.put(host, sslConnectionSocketFactory);
    }
    public static void addBasicCredentials(String host, Integer port, String user, String password) {
        if (host == null || port == null || user == null || password == null) {
            throw new IllegalArgumentException("must init trust store first.");
        }
        String key = host + ":" + port;
        if (credentialsProviderMap.containsKey(key)) {
            return;
        }
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(host, port),
                new org.apache.http.auth.UsernamePasswordCredentials(user, password));
        credentialsProviderMap.put(key, credentialsProvider);
    }
    public static HTTPResponse get(String url) {
        return use(url).get(url);
    }
    public static HTTPResponse get(String url, Map<String, String> params) {
        return use(url).get(url, params);
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers) {
        return use(url).get(url, params, headers);
    }
    public static HTTPResponse post(String url) {
        return use(url).post(url);
    }
    public static HTTPResponse post(String url, Map<String, String> params) {
        return use(url).post(url, params);
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {
        return use(url).post(url, params, headers);
    }
    public static HTTPResponse postFile(String url, String path) {
        return use(url).postFile(url, path);
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params) {
        return use(url).postFile(url, path, params);
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        return use(url).postFile(url, path, params, headers);
    }
    public static HTTPResponse put(String url) {
        return use(url).put(url);
    }
    public static HTTPResponse put(String url, Map<String, String> params) {
        return use(url).put(url, params);
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers) {
        return use(url).put(url, params, headers);
    }
    public static HTTPResponse delete(String url) {
        return use(url).delete(url);
    }
    public static HTTPResponse delete(String url, Map<String, String> params) {
        return use(url).delete(url, params);
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers) {
        return use(url).delete(url, params, headers);
    }
    public static HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers) {
        return use(url).request(method, url, params, headers);
    }
}

+ 104 - 0
hos-http/src/test/java/com/yihu/hos/http/HttpClientKitTest.java

@ -0,0 +1,104 @@
package com.yihu.hos.http;
import org.junit.Test;
/**
 * @created Airhead 2016/8/25.
 */
public class HttpClientKitTest {
    @Test
    public void use() throws Exception {
    }
    @Test
    public void addTrustStore() throws Exception {
    }
    @Test
    public void addBasicCredentials() throws Exception {
    }
    @Test
    public void get() throws Exception {
    }
    @Test
    public void get1() throws Exception {
    }
    @Test
    public void get2() throws Exception {
    }
    @Test
    public void post() throws Exception {
    }
    @Test
    public void post1() throws Exception {
    }
    @Test
    public void post2() throws Exception {
    }
    @Test
    public void postFile() throws Exception {
    }
    @Test
    public void postFile1() throws Exception {
    }
    @Test
    public void postFile2() throws Exception {
    }
    @Test
    public void put() throws Exception {
    }
    @Test
    public void put1() throws Exception {
    }
    @Test
    public void put2() throws Exception {
    }
    @Test
    public void delete() throws Exception {
    }
    @Test
    public void delete1() throws Exception {
    }
    @Test
    public void delete2() throws Exception {
    }
    @Test
    public void request() throws Exception {
    }
}