包名修改

This commit is contained in:
zzs
2017-04-10 09:22:17 +08:00
parent 174f602dd7
commit 7152f001e4
100 changed files with 564 additions and 515 deletions

View File

@@ -0,0 +1,182 @@
package com.egzosn.pay.common.http;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.result.PayException;
import com.egzosn.pay.common.util.XML;
import com.egzosn.pay.common.exception.PayErrorException;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Map;
import static com.egzosn.pay.common.http.UriVariables.getMapToParameters;
/**
* 一个HTTP请求的客户端
* @author: egan
* @email egzosn@gmail.com
* @date 2017/3/4 17:56
*/
public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase implements org.apache.http.client.ResponseHandler<T>{
//http请求
private MethodType method;
//响应类型
private Class<T> responseType;
public ClientHttpRequest<T> setResponseType(Class<T> responseType) {
this.responseType = responseType;
return this;
}
public ClientHttpRequest() {
}
public ClientHttpRequest(URI uri, MethodType method, Object request) {
this.setURI(uri);
this.method = method;
setParameters(request);
}
public ClientHttpRequest(URI uri, MethodType method) {
this.setURI(uri);
this.method = method;
}
public ClientHttpRequest(URI uri) {
this.setURI(uri);
}
public ClientHttpRequest(String uri) {
this.setURI(URI.create(uri));
}
public ClientHttpRequest(String uri, MethodType method) {
this.setURI(URI.create(uri));
this.method = method;
}
public ClientHttpRequest(String uri, MethodType method, Object request) {
this.setURI(URI.create(uri));
this.method = method;
setParameters(request);
}
public void setMethod(MethodType method) {
this.method = method;
}
@Override
public String getMethod() {
return method.name();
}
/**
* 设置代理
* @param httpProxy http代理配置信息
* @return
*/
public ClientHttpRequest setProxy(HttpHost httpProxy){
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
setConfig(config);
}
return this;
}
/**
* 设置请求参数
*
* @param request 请求参数
* @return
*/
public ClientHttpRequest setParameters(Object request) {
if (null == request){
return this;
}
if (request instanceof Map) {
StringEntity entity = new StringEntity(getMapToParameters((Map) request), Consts.UTF_8);
setEntity(entity);
} else if (request instanceof String) {
StringEntity entity = new StringEntity((String) request, Consts.UTF_8);
setEntity(entity);
} else {
StringEntity entity = new StringEntity(JSON.toJSONString(request), ContentType.APPLICATION_JSON);
setEntity(entity);
}
return this;
}
@Override
public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
final StatusLine statusLine = response.getStatusLine();
final HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300 && statusLine.getStatusCode() != 304) {
EntityUtils.consume(entity);
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
if (null == responseType){
responseType = (Class<T>) String.class;
}
String[] value = entity.getContentType().getValue().split(";");
if (ContentType.APPLICATION_OCTET_STREAM.getMimeType().equals(value[0])){
if (responseType.isAssignableFrom(InputStream.class)){
return (T)entity.getContent();
}
if (responseType.isAssignableFrom(OutputStream.class)){
try {
T t = responseType.newInstance();
entity.writeTo((OutputStream)t);
return t;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
throw new HttpResponseException(statusLine.getStatusCode(), responseType + " 无法进行类型转换");
}
}
String charset = "UTF-8";
if (null != value && 2 == charset.length()) {
charset = value[1].substring(value[1].indexOf("=") + 1);
}
String result = EntityUtils.toString(entity, charset);
if (responseType.isAssignableFrom(String.class)){
return (T)result;
}
String frist = result.substring(0, 1);
if ( ContentType.APPLICATION_JSON.getMimeType().equals( value[0]) || "{[".indexOf(frist) >= 0 ){
try {
return JSON.parseObject(result, responseType);
}catch (JSONException e){
throw new PayErrorException(new PayException("failure", "类型转化异常,contentType:" + entity.getContentType().getValue(), result));
}
}
if (ContentType.APPLICATION_XML.getMimeType().equals( value[0]) || "<".indexOf(frist) >= 0){
return XML.toJSONObject(result).toJavaObject(responseType);
}
throw new PayErrorException(new PayException("failure", "类型转化异常,contentType:" + entity.getContentType().getValue(), result));
}
}

View File

@@ -0,0 +1,70 @@
package com.egzosn.pay.common.http;
/**
* HTTP 配置
* @author: egan
* @email egzosn@gmail.com
* @date 2017/3/3 20:48
*/
public class HttpConfigStorage {
//http代理地址
protected String httpProxyHost;
//代理端口
protected int httpProxyPort;
//代理用户名
protected String httpProxyUsername;
//代理密码
protected String httpProxyPassword;
/**
* http代理地址
* @return
*/
public String getHttpProxyHost() {
return httpProxyHost;
}
public void setHttpProxyHost(String httpProxyHost) {
this.httpProxyHost = httpProxyHost;
}
/**
* 代理端口
* @return
*/
public int getHttpProxyPort() {
return httpProxyPort;
}
public void setHttpProxyPort(int httpProxyPort) {
this.httpProxyPort = httpProxyPort;
}
/**
* 代理用户名
* @return
*/
public String getHttpProxyUsername() {
return httpProxyUsername;
}
public void setHttpProxyUsername(String httpProxyUsername) {
this.httpProxyUsername = httpProxyUsername;
}
/**
* 代理密码
* @return
*/
public String getHttpProxyPassword() {
return httpProxyPassword;
}
public void setHttpProxyPassword(String httpProxyPassword) {
this.httpProxyPassword = httpProxyPassword;
}
}

View File

@@ -0,0 +1,179 @@
package com.egzosn.pay.common.http;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.util.str.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
/**
* http请求工具
* @author: egan
* @email egzosn@gmail.com
* @date 2017/3/3 21:33
*/
public class HttpRequestTemplate {
protected CloseableHttpClient httpClient;
protected HttpHost httpProxy;
public HttpHost getHttpProxy() {
return httpProxy;
}
public CloseableHttpClient getHttpClient() {
return httpClient;
}
public HttpRequestTemplate(HttpConfigStorage configStorage) {
setHttpConfigStorage(configStorage);
}
public HttpRequestTemplate() {
setHttpConfigStorage(null);
}
public HttpRequestTemplate setHttpConfigStorage(HttpConfigStorage configStorage){
if (null == configStorage){
httpClient = HttpClients.createDefault();
return this;
}
if (StringUtils.isNotBlank(configStorage.getHttpProxyHost())) {
// 使用代理服务器
if (StringUtils.isNotBlank(configStorage.getHttpProxyUsername())) {
// 需要用户认证的代理服务器
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort()),
new UsernamePasswordCredentials(configStorage.getHttpProxyUsername(), configStorage.getHttpProxyPassword()));
httpClient = HttpClients
.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
} else {
// 无需用户认证的代理服务器
httpClient = HttpClients.createDefault();
}
httpProxy = new HttpHost(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort());
} else {
httpClient = HttpClients.createDefault();
}
return this;
}
/**
*
* post
* @param uri 请求地址
* @param request
* @param responseType 为响应类(需要自己依据响应格式来确定)
* @param <T>
* @return
* @throws IOException
*/
public <T> T postForObject(String uri, Object request, Class<T> responseType, Object... uriVariables){
return doExecute(URI.create(UriVariables.getUri(uri, uriVariables)), request, responseType, MethodType.POST);
}
public <T> T postForObject(String uri, Object request, Class<T> responseType, Map<String, Object> uriVariables) {
return doExecute(URI.create(UriVariables.getUri(uri, uriVariables)), request, responseType, MethodType.POST);
}
public <T> T postForObject(URI uri, Object request, Class<T> responseType){
return doExecute(uri, request, responseType, MethodType.POST);
}
/**
* get 请求
* @param uri 请求地址
* @param responseType 响应类型
* @param uriVariables 用于匹配表达式
* @param <T> 响应类型
* @return
*
* <code>
* getForObject("http://egan.in/pay/{id}/f/{type}", String.class, "1", "APP")
* </code>
*/
public <T> T getForObject(String uri, Class<T> responseType, Object... uriVariables){
return doExecute(URI.create(UriVariables.getUri(uri, uriVariables)), null, responseType, MethodType.GET);
}
/**
* get 请求
*
* @param uri 请求地址
* @param responseType 响应类型
* @param uriVariables 用于匹配表达式
* @param <T> 响应类型
* @return
* <code>
* Map<String, String> uriVariables = new HashMap<String, String>();
* uriVariables.put("id", "1");
* uriVariables.put("type", "APP");
* getForObject("http://egan.in/pay/{id}/f/{type}", String.class, uriVariables)
* </code>
*/
public <T> T getForObject(String uri, Class<T> responseType, Map<String, ?> uriVariables){
return doExecute(URI.create(UriVariables.getUri(uri, uriVariables)), null, responseType, MethodType.GET);
}
/**
* http 请求执行
* @param uri 地址
* @param request 请求数据
* @param responseType 响应类型
* @param method 请求方法
* @param <T>
* @return
* @throws IOException
*/
public <T>T doExecute(URI uri, Object request, Class<T> responseType, MethodType method){
ClientHttpRequest<T> httpRequest = new ClientHttpRequest(uri ,method, request);
httpRequest.setProxy(httpProxy).setResponseType(responseType);
try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
return httpRequest.handleResponse(response);
}catch ( IOException e){
e.printStackTrace();
}finally {
httpRequest.releaseConnection();
}
return null;
}
/**
* http 请求执行
* @param uri 地址
* @param request 请求数据
* @param responseType 响应类型
* @param method 请求方法
* @param <T>
* @return
* @throws IOException
*/
public <T>T doExecute(String uri, Object request, Class<T> responseType, MethodType method){
return doExecute(URI.create(uri), request, responseType, method);
}
}

View File

@@ -0,0 +1,130 @@
package com.egzosn.pay.common.http;
import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* URL表达式处理器
*
* @author: egan
* @email egzosn@gmail.com
* @date 2017/3/5 10:07
*/
public class UriVariables {
/**
* 依次匹配
* @param uri
* @param uriVariables
* @return
* <code>
* System.out.println(getUri("http://egan.in/{a}/ba/{a1}?{bb}={a1}", "no1", "no2", "no3", "no4"));
* 结果 http://egan.in/no1/ba/no2?no3=no4
* </code>
*
*/
public static String getUri(String uri, Object... uriVariables) {
if (null == uriVariables){
return uri;
}
for (Object variable : uriVariables){
if (null == variable){
continue;
}
uri = uri.replaceFirst("\\{\\w+\\}", variable.toString());
}
return uri;
}
/**
* 匹配Map.key
* @param uri
* @param uriVariables
* @return
* <code>
* Map<String, Object> uriVariable = new HashMap<>();
* uriVariable.put("a", "no1");
* uriVariable.put("a1", "no2");
* uriVariable.put("bb", "no3");
* System.out.println(getUri("http://egan.in/{a}/ba/{a1}?{bb}={a1}", uriVariable));
* 结果 http://egan.in/no1/ba/no2?no3=no2
* </code>
*/
public static String getUri(String uri, Map<String, Object> uriVariables) {
if (null == uriVariables){
return uri;
}
for (String key : uriVariables.keySet()){
Object uriVariable = uriVariables.get(key);
if (null == uriVariable){
continue;
}
uri = uri.replace("{" + key + "}", uriVariable.toString());
}
return uri;
}
/**
* Map转化为对应得参数字符串
* @param pe
* @return
*/
public static String getMapToParameters(Map pe){
StringBuilder builder = new StringBuilder();
for (Object key : pe.keySet()) {
Object o = pe.get(key);
if (null == o) {
continue;
}
if (o instanceof List) {
o = ((List) o).toArray();
}
try {
if (o instanceof Object[]) {
Object[] os = (Object[]) o;
String valueStr = "";
for (int i = 0, len = os.length; i < len; i++) {
if (null == os[i]) {
continue;
}
String value = os[i].toString().trim();
valueStr += (i == len - 1) ? value : value + ",";
}
builder.append(key).append("=").append(URLEncoder.encode(valueStr, "utf-8")).append("&");
continue;
}
builder.append(key).append("=").append(URLEncoder.encode((String) pe.get(key), "utf-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if (builder.length() > 1) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
}