diff --git a/.gitignore b/.gitignore index 5ebc850..7c5a415 100644 --- a/.gitignore +++ b/.gitignore @@ -46,10 +46,11 @@ hs_err_pid* *.dmg *.gz *.iso -*.jar *.rar *.tar *.zip + +Local*Test.java # Logs and databases # ###################### @@ -61,9 +62,10 @@ hs_err_pid* ###################### .DS_Store .DS_Store? -._* .Spotlight-V100 .Trashes Icon? ehthumbs.db Thumbs.db + + diff --git a/pom.xml b/pom.xml index 526605f..31837dc 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ httpclientutil 1.0.5-SNAPSHOT ${project.artifactId} - 基于HttpClient-4.4.1封装的工具类。支持插件式配置Header、插件式配置httpclient对象,这样就可以方便地自定义header信息、配置ssl、配置proxy、Cookie等 + 基于HttpClient-4.5.6封装的工具类。支持插件式配置Header、插件式配置httpclient对象,这样就可以方便地自定义header信息、配置ssl、配置proxy、Cookie等 @@ -13,12 +13,13 @@ UTF-8 UTF-8 - 4.4.1 + 4.5.6 2.10.3 2.4 1.6 1.6.8 + 1.2.3 @@ -44,16 +45,21 @@ httpasyncclient 4.1 - - log4j - log4j - 1.2.17 + ch.qos.logback + logback-classic + ${logback.version} + + ch.qos.logback + logback-core + ${logback.version} + + + + + + @@ -67,6 +73,8 @@ https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + diff --git a/src/main/java/com/arronlong/httpclientutil/HttpClientUtil.java b/src/main/java/com/arronlong/httpclientutil/HttpClientUtil.java index 79c5ed3..3d94321 100644 --- a/src/main/java/com/arronlong/httpclientutil/HttpClientUtil.java +++ b/src/main/java/com/arronlong/httpclientutil/HttpClientUtil.java @@ -1,36 +1,25 @@ package com.arronlong.httpclientutil; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import com.arronlong.httpclientutil.builder.HCB; +import com.arronlong.httpclientutil.common.HttpConfig; +import com.arronlong.httpclientutil.common.HttpMethods; +import com.arronlong.httpclientutil.common.HttpResult; +import com.arronlong.httpclientutil.common.Utils; +import com.arronlong.httpclientutil.exception.HttpProcessException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpOptions; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpTrace; +import org.apache.http.client.methods.*; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; -import com.arronlong.httpclientutil.builder.HCB; -import com.arronlong.httpclientutil.common.HttpConfig; -import com.arronlong.httpclientutil.common.HttpMethods; -import com.arronlong.httpclientutil.common.HttpResult; -import com.arronlong.httpclientutil.common.Utils; -import com.arronlong.httpclientutil.exception.HttpProcessException; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; /** * 使用HttpClient模拟发送(http/https)请求 @@ -374,7 +363,7 @@ public static int status(HttpConfig config) throws HttpProcessException { * @throws HttpProcessException http处理异常 */ public static String send(HttpConfig config) throws HttpProcessException { - return fmt2String(execute(config), config.outenc()); + return fmt2String(execute(config), config.outputEncoding()); } /** @@ -390,7 +379,7 @@ public static HttpResult sendAndGetResp(HttpConfig config) throws HttpProcessExc HttpResponse resp = execute(config); HttpResult result = new HttpResult(resp); - result.setResult(fmt2String(resp, config.outenc())); + result.setResult(fmt2String(resp, config.outputEncoding())); result.setReqHeaders(reqHeaders); return result; @@ -424,11 +413,11 @@ private static HttpResponse execute(HttpConfig config) throws HttpProcessExcepti if(request.getClass()==HttpGet.class) { //检测url中是否存在参数 //注:只有get请求,才自动截取url中的参数,post等其他方式,不再截取 - config.url(Utils.checkHasParas(config.url(), nvps, config.inenc())); + config.url(Utils.checkHasParas(config.url(), nvps, config.inputEncoding())); } //装填参数 - HttpEntity entity = Utils.map2HttpEntity(nvps, config.map(), config.inenc()); + HttpEntity entity = Utils.map2HttpEntity(nvps, config.map(), config.inputEncoding()); //设置参数到请求对象中 ((HttpEntityEnclosingRequestBase)request).setEntity(entity); diff --git a/src/main/java/com/arronlong/httpclientutil/common/HttpConfig.java b/src/main/java/com/arronlong/httpclientutil/common/HttpConfig.java index c586554..26c6f95 100644 --- a/src/main/java/com/arronlong/httpclientutil/common/HttpConfig.java +++ b/src/main/java/com/arronlong/httpclientutil/common/HttpConfig.java @@ -1,15 +1,15 @@ package com.arronlong.httpclientutil.common; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; - import org.apache.http.Header; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.protocol.HttpContext; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + //import com.tgb.ccl.http.exception.HttpProcessException; //import com.tgb.ccl.http.httpclient.builder.HCB; @@ -50,11 +50,6 @@ public static HttpConfig custom(){ * 请求方法 */ private HttpMethods method=HttpMethods.GET; - - /** - * 请求方法名称 - */ - private String methodName; /** * 用于cookie操作 @@ -64,13 +59,18 @@ public static HttpConfig custom(){ /** * 传递参数 */ -// private Map map; + private Map map = new HashMap(8); /** * 以json格式作为输入参数 */ private String json; + /** + * 链接 + */ + private String url; + /** * 输入输出编码 */ @@ -79,12 +79,12 @@ public static HttpConfig custom(){ /** * 输入编码 */ - private String inenc; + private String inputEncoding; /** * 输出编码 */ - private String outenc; + private String outputEncoding; /** * 设置RequestConfig @@ -94,17 +94,7 @@ public static HttpConfig custom(){ /** * 解决多线程下载时,strean被close的问题 */ - private static final ThreadLocal outs = new ThreadLocal(); - - /** - * 解决多线程处理时,url被覆盖问题 - */ - private static final ThreadLocal urls = new ThreadLocal(); - - /** - * 解决多线程处理时,url被覆盖问题 - */ - private static final ThreadLocal> maps = new ThreadLocal>(); + private final ThreadLocal outs = new ThreadLocal(); /** * @param client HttpClient对象 @@ -120,7 +110,7 @@ public HttpConfig client(HttpClient client) { * @return 返回当前对象 */ public HttpConfig url(String url) { - urls.set(url); + this.url = url; return this; } @@ -155,15 +145,6 @@ public HttpConfig method(HttpMethods method) { return this; } - /** - * @param methodName 请求方法 - * @return 返回当前对象 - */ - public HttpConfig methodName(String methodName) { - this.methodName = methodName; - return this; - } - /** * @param context cookie操作相关 * @return 返回当前对象 @@ -178,20 +159,7 @@ public HttpConfig context(HttpContext context) { * @return 返回当前对象 */ public HttpConfig map(Map map) { -// synchronized (getClass()) { -// if(this.map==null || map==null){ -// this.map = map; -// }else { -// this.map.putAll(map);; -// } -// } - Map m = maps.get(); - if(m==null || m==null || map==null){ - m = map; - }else { - m.putAll(map); - } - maps.set(m); + this.map = map; return this; } @@ -201,9 +169,6 @@ public HttpConfig map(Map map) { */ public HttpConfig json(String json) { this.json = json; - Map map = new HashMap(); - map.put(Utils.ENTITY_JSON, json); - maps.set(map); return this; } @@ -231,23 +196,9 @@ public HttpConfig files(String[] filePaths, String inputName) { * @return 返回当前对象 */ public HttpConfig files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) { -// synchronized (getClass()) { -// if(this.map==null){ -// this.map= new HashMap(); -// } -// } -// map.put(Utils.ENTITY_MULTIPART, filePaths); -// map.put(Utils.ENTITY_MULTIPART+".name", inputName); -// map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); - - Map m = maps.get(); - if(m==null || m==null){ - m = new HashMap(); - } - m.put(Utils.ENTITY_MULTIPART, filePaths); - m.put(Utils.ENTITY_MULTIPART+".name", inputName); - m.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); - maps.set(m); + this.map.put(Utils.ENTITY_MULTIPART, filePaths); + this.map.put(Utils.ENTITY_MULTIPART+".name", inputName); + this.map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); return this; } @@ -257,27 +208,27 @@ public HttpConfig files(String[] filePaths, String inputName, boolean forceRemov */ public HttpConfig encoding(String encoding) { //设置输入输出 - inenc(encoding); - outenc(encoding); + inputEncoding(encoding); + outputEncoding(encoding); this.encoding = encoding; return this; } /** - * @param inenc 输入编码 + * @param inputEncoding 输入编码 * @return 返回当前对象 */ - public HttpConfig inenc(String inenc) { - this.inenc = inenc; + public HttpConfig inputEncoding(String inputEncoding) { + this.inputEncoding = inputEncoding; return this; } /** - * @param outenc 输出编码 + * @param outputEncoding 输出编码 * @return 返回当前对象 */ - public HttpConfig outenc(String outenc) { - this.outenc = outenc; + public HttpConfig outputEncoding(String outputEncoding) { + this.outputEncoding = outputEncoding; return this; } @@ -341,24 +292,20 @@ public boolean isReturnRespHeaders() { } public String url() { - return urls.get(); + return url; } public HttpMethods method() { return method; } - public String methodName() { - return methodName; - } public HttpContext context() { return context; } public Map map() { -// return map; - return maps.get(); + return map; } public String json() { @@ -369,12 +316,12 @@ public String encoding() { return encoding; } - public String inenc() { - return inenc == null ? encoding : inenc; + public String inputEncoding() { + return inputEncoding == null ? encoding : inputEncoding; } - public String outenc() { - return outenc == null ? encoding : outenc; + public String outputEncoding() { + return outputEncoding == null ? encoding : outputEncoding; } public OutputStream out() { diff --git a/src/main/java/com/arronlong/httpclientutil/common/Utils.java b/src/main/java/com/arronlong/httpclientutil/common/Utils.java index 61d8e3b..1b1eda3 100644 --- a/src/main/java/com/arronlong/httpclientutil/common/Utils.java +++ b/src/main/java/com/arronlong/httpclientutil/common/Utils.java @@ -1,17 +1,5 @@ package com.arronlong.httpclientutil.common; -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; @@ -24,281 +12,268 @@ import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.charset.Charset; +import java.util.*; +import java.util.Map.Entry; + +/** * 工具类 - * - * 用于设定参数特定类型 - * 启用bebug模式,打印消息 - * + *

+ * 用于设定参数特定类型 + * 启用bebug模式,打印消息 + * * @author arron - * @version 1.0 + * @version 1.0 */ public class Utils { - - //传入参数特定类型 - public static final String ENTITY_STRING="$ENTITY_STRING$"; - public static final String ENTITY_JSON="$ENTITY_JSON$"; - public static final String ENTITY_FILE="$ENTITY_FILEE$"; - public static final String ENTITY_BYTES="$ENTITY_BYTES$"; - public static final String ENTITY_INPUTSTREAM="$ENTITY_INPUTSTREAM$"; - public static final String ENTITY_SERIALIZABLE="$ENTITY_SERIALIZABLE$"; - public static final String ENTITY_MULTIPART="$ENTITY_MULTIPART$"; - private static final List SPECIAL_ENTITIY = Arrays.asList(ENTITY_STRING, ENTITY_JSON, ENTITY_BYTES, ENTITY_FILE, ENTITY_INPUTSTREAM, ENTITY_SERIALIZABLE, ENTITY_MULTIPART); - - /** - * 是否开启debug, - */ - private static boolean debug = false; - private static final Logger logger = Logger.getLogger("HttpClient(异步)工具类"); - /** - * 检测url是否含有参数,如果有,则把参数加到参数列表中 - * - * @param url 资源地址 - * @param nvps 参数列表 - * @param encoding 编码 - * @return 返回去掉参数的url - * @throws UnsupportedEncodingException 不支持的编码异常 - */ - public static String checkHasParas(String url, List nvps, String encoding) throws UnsupportedEncodingException { - // 检测url中是否存在参数 - if (url.contains("?") && url.indexOf("?") < url.indexOf("=")) { - Map map = buildParas(url.substring(url.indexOf("?") + 1)); - map2HttpEntity(nvps, map, encoding); - url = url.substring(0, url.indexOf("?")); - } - return url; - } + //传入参数特定类型 + public static final String ENTITY_STRING = "$ENTITY_STRING$"; + public static final String ENTITY_JSON = "$ENTITY_JSON$"; + public static final String ENTITY_FILE = "$ENTITY_FILEE$"; + public static final String ENTITY_BYTES = "$ENTITY_BYTES$"; + public static final String ENTITY_INPUTSTREAM = "$ENTITY_INPUTSTREAM$"; + public static final String ENTITY_SERIALIZABLE = "$ENTITY_SERIALIZABLE$"; + public static final String ENTITY_MULTIPART = "$ENTITY_MULTIPART$"; + private static final List SPECIAL_ENTITIY = Arrays.asList(ENTITY_STRING, ENTITY_JSON, ENTITY_BYTES, ENTITY_FILE, ENTITY_INPUTSTREAM, ENTITY_SERIALIZABLE, ENTITY_MULTIPART); + + + private static final Logger logger = LoggerFactory.getLogger(Utils.class); - /** - * - * 参数转换,将map中的参数,转到参数列表中 - * - * @param nvps 参数列表 - * @param map 参数列表(map) - * @param encoding 编码 - * @return 返回HttpEntity - * @throws UnsupportedEncodingException 不支持的编码异常 - */ - public static HttpEntity map2HttpEntity(List nvps, Map map, String encoding) throws UnsupportedEncodingException { - HttpEntity entity = null; - if(map!=null && map.size()>0){ - boolean isSpecial = false; - // 拼接参数 - for (Entry entry : map.entrySet()) { - if(SPECIAL_ENTITIY.contains(entry.getKey())){//判断是否在之中 - isSpecial = true; - if(ENTITY_STRING.equals(entry.getKey())){//string - entity = new StringEntity(String.valueOf(entry.getValue()), encoding); - break; - }else if(ENTITY_JSON.equals(entry.getKey())){//json - entity = new StringEntity(String.valueOf(entry.getValue()), encoding); - String contentType = "application/json"; - if (encoding != null) { - contentType += ";charset=" + encoding; - } - ((StringEntity) entity).setContentType(contentType); - break; - }else if(ENTITY_BYTES.equals(entry.getKey())){//file - entity = new ByteArrayEntity((byte[])entry.getValue()); - break; - }else if(ENTITY_FILE.equals(entry.getKey())){//file - if(File.class.isAssignableFrom(entry.getValue().getClass())){ - entity = new FileEntity((File)entry.getValue(), ContentType.APPLICATION_OCTET_STREAM); - }else if(entry.getValue().getClass()==String.class){ - entity = new FileEntity(new File((String) entry.getValue()), ContentType.create("text/plain", "UTF-8")); - } - break; - }else if(ENTITY_INPUTSTREAM.equals(entry.getKey())){//inputstream + /** + * 检测url是否含有参数,如果有,则把参数加到参数列表中 + * + * @param url 资源地址 + * @param nvps 参数列表 + * @param encoding 编码 + * @return 返回去掉参数的url + * @throws UnsupportedEncodingException 不支持的编码异常 + */ + public static String checkHasParas(String url, List nvps, String encoding) throws UnsupportedEncodingException { + // 检测url中是否存在参数 + if (url.contains("?") && url.indexOf("?") < url.indexOf("=")) { + Map map = buildParas(url.substring(url.indexOf("?") + 1)); + map2HttpEntity(nvps, map, encoding); + url = url.substring(0, url.indexOf("?")); + } + return url; + } + + /** + * 参数转换,将map中的参数,转到参数列表中 + * + * @param nvps 参数列表 + * @param map 参数列表(map) + * @param encoding 编码 + * @return 返回HttpEntity + * @throws UnsupportedEncodingException 不支持的编码异常 + */ + public static HttpEntity map2HttpEntity(List nvps, Map map, String encoding) throws UnsupportedEncodingException { + HttpEntity entity = null; + if (map != null && map.size() > 0) { + boolean isSpecial = false; + // 拼接参数 + for (Entry entry : map.entrySet()) { + if (SPECIAL_ENTITIY.contains(entry.getKey())) {//判断是否在之中 + isSpecial = true; + if (ENTITY_STRING.equals(entry.getKey())) {//string + entity = new StringEntity(String.valueOf(entry.getValue()), encoding); + break; + } else if (ENTITY_JSON.equals(entry.getKey())) {//json + entity = new StringEntity(String.valueOf(entry.getValue()), encoding); + String contentType = "application/json"; + if (encoding != null) { + contentType += ";charset=" + encoding; + } + ((StringEntity) entity).setContentType(contentType); + break; + } else if (ENTITY_BYTES.equals(entry.getKey())) {//file + entity = new ByteArrayEntity((byte[]) entry.getValue()); + break; + } else if (ENTITY_FILE.equals(entry.getKey())) {//file + if (File.class.isAssignableFrom(entry.getValue().getClass())) { + entity = new FileEntity((File) entry.getValue(), ContentType.APPLICATION_OCTET_STREAM); + } else if (entry.getValue().getClass() == String.class) { + entity = new FileEntity(new File((String) entry.getValue()), ContentType.create("text/plain", "UTF-8")); + } + break; + } else if (ENTITY_INPUTSTREAM.equals(entry.getKey())) {//inputstream // entity = new InputStreamEntity(); - break; - }else if(ENTITY_SERIALIZABLE.equals(entry.getKey())){//serializeable + break; + } else if (ENTITY_SERIALIZABLE.equals(entry.getKey())) {//serializeable // entity = new SerializableEntity() - break; - }else if(ENTITY_MULTIPART.equals(entry.getKey())){//MultipartEntityBuilder - File[] files = null; - if(File.class.isAssignableFrom(entry.getValue().getClass().getComponentType())){ - files=(File[])entry.getValue(); - }else if(entry.getValue().getClass().getComponentType()==String.class){ - String[] names = (String[]) entry.getValue(); - files = new File[names.length]; - for (int i = 0; i < names.length; i++) { - files[i] = new File(names[i]); - } - } - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setCharset(Charset.forName(encoding));// 设置请求的编码格式 - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式 - int count = 0; - for (File file : files) { + break; + } else if (ENTITY_MULTIPART.equals(entry.getKey())) {//MultipartEntityBuilder + File[] files = null; + if (File.class.isAssignableFrom(entry.getValue().getClass().getComponentType())) { + files = (File[]) entry.getValue(); + } else if (entry.getValue().getClass().getComponentType() == String.class) { + String[] names = (String[]) entry.getValue(); + files = new File[names.length]; + for (int i = 0; i < names.length; i++) { + files[i] = new File(names[i]); + } + } + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setCharset(Charset.forName(encoding));// 设置请求的编码格式 + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式 + int count = 0; + for (File file : files) { // //把文件转换成流对象FileBody // FileBody fileBody = new FileBody(file); // builder.addPart(String.valueOf(map.get(ENTITY_MULTIPART+".name")) + count++, fileBody); - builder.addBinaryBody(String.valueOf(map.get(ENTITY_MULTIPART+".name")) + count++,file); - } - boolean forceRemoveContentTypeCharset = (Boolean)map.get(ENTITY_MULTIPART+".rmCharset"); - Map m = new HashMap(); - m.putAll(map); - m.remove(ENTITY_MULTIPART); - m.remove(ENTITY_MULTIPART+".name"); - m.remove(ENTITY_MULTIPART+".rmCharset"); - Iterator> iterator = m.entrySet().iterator(); - // 发送的数据 - while (iterator.hasNext()) { - Entry e = iterator.next(); - builder.addTextBody(e.getKey(), String.valueOf(e.getValue()), ContentType.create("text/plain", encoding)); - } - entity = builder.build();// 生成 HTTP POST 实体 - - //强制去除contentType中的编码设置,否则,在某些情况下会导致上传失败 - if(forceRemoveContentTypeCharset){ - removeContentTypeCharset(encoding, entity); - } - break; - }else { - nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); - } - }else{ - nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); - } - } - if(!isSpecial) { - entity = new UrlEncodedFormEntity(nvps, encoding); - } - } - return entity; - } + builder.addBinaryBody(String.valueOf(map.get(ENTITY_MULTIPART + ".name")) + count++, file); + } + boolean forceRemoveContentTypeCharset = (Boolean) map.get(ENTITY_MULTIPART + ".rmCharset"); + Map m = new HashMap(); + m.putAll(map); + m.remove(ENTITY_MULTIPART); + m.remove(ENTITY_MULTIPART + ".name"); + m.remove(ENTITY_MULTIPART + ".rmCharset"); + Iterator> iterator = m.entrySet().iterator(); + // 发送的数据 + while (iterator.hasNext()) { + Entry e = iterator.next(); + builder.addTextBody(e.getKey(), String.valueOf(e.getValue()), ContentType.create("text/plain", encoding)); + } + entity = builder.build();// 生成 HTTP POST 实体 + + //强制去除contentType中的编码设置,否则,在某些情况下会导致上传失败 + if (forceRemoveContentTypeCharset) { + removeContentTypeCharset(encoding, entity); + } + break; + } else { + nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); + } + } else { + nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); + } + } + if (!isSpecial) { + entity = new UrlEncodedFormEntity(nvps, encoding); + } + } + return entity; + } + + /** + * 移除content-type中的charset + * + * @param encoding 编码 + * @param entity 请求参数及数据信息 + */ + private static void removeContentTypeCharset(String encoding, HttpEntity entity) { + try { + Class clazz = entity.getClass(); + Field field = clazz.getDeclaredField("contentType"); + field.setAccessible(true); //将字段的访问权限设为true:即去除private修饰符的影响 + if (Modifier.isFinal(field.getModifiers())) { + Field modifiersField = Field.class.getDeclaredField("modifiers"); //去除final修饰符的影响,将字段设为可修改的 + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + } + BasicHeader o = (BasicHeader) field.get(entity); + field.set(entity, new BasicHeader(HTTP.CONTENT_TYPE, o.getValue().replace("; charset=" + encoding, ""))); + } catch (NoSuchFieldException e) { + Utils.exception(e); + } catch (SecurityException e) { + Utils.exception(e); + } catch (IllegalArgumentException e) { + Utils.exception(e); + } catch (IllegalAccessException e) { + Utils.exception(e); + } + } + + + /** + * 生成参数 + * 参数格式:k1=v1&k2=v2 + * + * @param paras 参数列表 + * @return 返回参数列表(map) + */ + public static Map buildParas(String paras) { + String[] p = paras.split("&"); + String[][] ps = new String[p.length][2]; + int pos = 0; + for (int i = 0; i < p.length; i++) { + pos = p[i].indexOf("="); + ps[i][0] = p[i].substring(0, pos); + ps[i][1] = p[i].substring(pos + 1); + pos = 0; + } + return buildParas(ps); + } + + /** + * 生成参数 + * 参数类型:{{"k1","v1"},{"k2","v2"}} + * + * @param paras 参数列表 + * @return 返回参数列表(map) + */ + public static Map buildParas(String[][] paras) { + // 创建参数队列 + Map map = new HashMap(); + for (String[] para : paras) { + map.put(para[0], para[1]); + } + return map; + } + + /** + * 打印消息 + * + * @param msg 消息 + */ + public static void info(String msg) { + logger.info(msg); + } + + /** + * 打印消息和异常堆栈 + * + * @param msg 异常消息 + * @param t 异常 + */ + public static void infoException(String msg, Throwable t) { + logger.info(msg, t); + } + + /** + * 打印错误消息 + * + * @param msg 异常消息 + */ + public static void error(String msg) { + logger.error(msg); + } - /** - * 移除content-type中的charset - * - * @param encoding 编码 - * @param entity 请求参数及数据信息 - */ - private static void removeContentTypeCharset(String encoding, HttpEntity entity) { - try { - Class clazz = entity.getClass(); - Field field = clazz.getDeclaredField("contentType"); - field.setAccessible(true); //将字段的访问权限设为true:即去除private修饰符的影响 - if(Modifier.isFinal(field.getModifiers())){ - Field modifiersField = Field.class.getDeclaredField("modifiers"); //去除final修饰符的影响,将字段设为可修改的 - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - } - BasicHeader o = (BasicHeader) field.get(entity); - field.set(entity, new BasicHeader(HTTP.CONTENT_TYPE, o.getValue().replace("; charset="+encoding,""))); - } catch (NoSuchFieldException e) { - Utils.exception(e); - } catch (SecurityException e) { - Utils.exception(e); - } catch (IllegalArgumentException e) { - Utils.exception(e); - } catch (IllegalAccessException e) { - Utils.exception(e); - } - } - - - /** - * 生成参数 - * 参数格式:k1=v1&k2=v2 - * - * @param paras 参数列表 - * @return 返回参数列表(map) - */ - public static Map buildParas(String paras){ - String[] p = paras.split("&"); - String[][] ps = new String[p.length][2]; - int pos = 0; - for (int i = 0; i < p.length; i++) { - pos = p[i].indexOf("="); - ps[i][0]=p[i].substring(0,pos); - ps[i][1]=p[i].substring(pos+1); - pos = 0; - } - return buildParas(ps); - } - - /** - * 生成参数 - * 参数类型:{{"k1","v1"},{"k2","v2"}} - * - * @param paras 参数列表 - * @return 返回参数列表(map) - */ - public static Map buildParas(String[][] paras){ - // 创建参数队列 - Map map = new HashMap(); - for (String[] para: paras) { - map.put(para[0], para[1]); - } - return map; - } - - /** - * 打印消息 - * - * @param msg 消息 - */ - public static void info(String msg){ - if(debug){ - logger.info(msg); - } - } - - /** - * 打印消息和异常堆栈 - * - * @param msg 异常消息 - * @param t 异常 - */ - public static void infoException(String msg, Throwable t){ - if(debug){ - logger.info(msg, t); - } - } - - /** - * 打印错误消息 - * - * @param msg 异常消息 - */ - public static void error(String msg){ - logger.error(msg); - } - - /** - * 打印错误消息和异常堆栈 - * - * @param msg 异常消息 - * @param t 异常 - */ - public static void errorException(String msg, Throwable t){ - logger.error(msg, t); - } - - /** - * 打印异常堆栈 - * - * @param t 异常 - */ - public static void exception(Throwable t){ - logger.error(t); - } + /** + * 打印错误消息和异常堆栈 + * + * @param msg 异常消息 + * @param t 异常 + */ + public static void errorException(String msg, Throwable t) { + logger.error(msg, t); + } - /** - * 开启打印日志 - */ - public static void debug() { - debug(true); - } - /** - * 开启或关闭打印日志 - * @param debug 是否开启debug - */ - public static void debug(boolean debug) { - Utils.debug = debug; - } + /** + * 打印异常堆栈 + * + * @param t 异常 + */ + public static void exception(Throwable t) { + logger.error("exception: ", t); + } } diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties deleted file mode 100644 index b34924d..0000000 --- a/src/main/resources/log4j.properties +++ /dev/null @@ -1,29 +0,0 @@ -### \u8bbe\u7f6e Logger \u8f93\u51fa\u7ea7\u522b\u548c\u8f93\u51fa\u76ee\u7684\u5730 ### - -log4j.rootLogger=INFO,stdout,logfile - -### \u628a\u65e5\u5fd7\u4fe1\u606f\u8f93\u51fa\u5230\u63a7\u5236\u53f0 ### - -log4j.appender.INFO=org.apache.log4j.ConsoleAppender -log4j.appender.INFO.layout=org.apache.log4j.PatternLayout -log4j.appender.INFO.layout.ConversionPattern=[%-5p] %L method:%l - %m%n - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -#log4j.appender.stdout.Target=System.err -log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout -#log4j.appender.stdout.layout.ConversionPattern=[%-5p] %L method:%l - %m%n - -### \u628a\u65e5\u5fd7\u4fe1\u606f\u8f93\u51fa\u5230\u6587\u4ef6 jbit.log ### - -#log4j.appender.logfile=org.apache.log4j.FileAppender -log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender - -log4j.appender.logfile.File=/logs/httpclient/httputil.log - -log4j.appender.logfile.DatePattern='.'yyyy-MM-dd - -log4j.appender.logfile.layout=org.apache.log4j.PatternLayout - -#log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n -log4j.appender.logfile.layout.ConversionPattern=[%-5p] %L-%d{yyyy-MM-dd HH:mm:ss,SSS} method:%l - %m%n - diff --git a/src/test/java/com/arronlong/httpclientutil/test/HttpClientTest.java b/src/test/java/com/arronlong/httpclientutil/test/HttpClientTest.java index 790b60d..50af671 100644 --- a/src/test/java/com/arronlong/httpclientutil/test/HttpClientTest.java +++ b/src/test/java/com/arronlong/httpclientutil/test/HttpClientTest.java @@ -1,5 +1,13 @@ package com.arronlong.httpclientutil.test; +import com.arronlong.httpclientutil.HttpClientUtil; +import com.arronlong.httpclientutil.builder.HCB; +import com.arronlong.httpclientutil.common.HttpConfig; +import com.arronlong.httpclientutil.common.HttpHeader; +import com.arronlong.httpclientutil.exception.HttpProcessException; +import org.apache.http.Header; +import org.apache.http.client.HttpClient; + import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -8,15 +16,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.apache.http.Header; -import org.apache.http.client.HttpClient; - -import com.arronlong.httpclientutil.HttpClientUtil; -import com.arronlong.httpclientutil.builder.HCB; -import com.arronlong.httpclientutil.common.HttpConfig; -import com.arronlong.httpclientutil.common.HttpHeader; -import com.arronlong.httpclientutil.exception.HttpProcessException; - /** * * @author arron @@ -163,7 +162,6 @@ public GetRunnable setConfig(HttpConfig config){ public GetRunnable(CountDownLatch countDownLatch){ this.countDownLatch = countDownLatch; } - @Override public void run() { try { if(config.out()==null){ diff --git a/src/test/java/com/arronlong/httpclientutil/test/LocalHttpClientTest.java b/src/test/java/com/arronlong/httpclientutil/test/LocalHttpClientTest.java new file mode 100644 index 0000000..1aaf1b2 --- /dev/null +++ b/src/test/java/com/arronlong/httpclientutil/test/LocalHttpClientTest.java @@ -0,0 +1,35 @@ +package com.arronlong.httpclientutil.test; + +import com.arronlong.httpclientutil.HttpClientUtil; +import com.arronlong.httpclientutil.common.HttpConfig; +import com.arronlong.httpclientutil.exception.HttpProcessException; +import org.apache.http.Header; +import org.apache.http.message.BasicHeader; + +import java.util.HashMap; +import java.util.Map; + +/** + * 本地测试方法 + * + * @author sharker + * @date 2019/7/18 14:53 + */ +public class LocalHttpClientTest { + + public static void main(String[] args) throws HttpProcessException { + final Object token = "b982e7b31a7b783007c057848009a932"; + String json = "{\"token\":\""+token+"\"}"; + Map map = new HashMap(){{ + put("token", token); + put("s", "asdfasdf"); + }}; + Header[] headers = new BasicHeader[]{ + new BasicHeader("token", token.toString()) + }; + HttpConfig httpConfig = HttpConfig.custom().json(json).url("http://localhost:8094/chat-messages/test").map(map).headers(headers); + String result = HttpClientUtil.post(httpConfig); + System.out.println("result: " + result); + } + +} diff --git a/src/test/java/com/arronlong/httpclientutil/test/TestUpload.java b/src/test/java/com/arronlong/httpclientutil/test/TestUpload.java index f0b17fe..8e4f52f 100644 --- a/src/test/java/com/arronlong/httpclientutil/test/TestUpload.java +++ b/src/test/java/com/arronlong/httpclientutil/test/TestUpload.java @@ -1,14 +1,13 @@ package com.arronlong.httpclientutil.test; -import java.util.HashMap; -import java.util.Map; - import com.arronlong.httpclientutil.HttpClientUtil; import com.arronlong.httpclientutil.common.HttpConfig; import com.arronlong.httpclientutil.common.HttpCookies; -import com.arronlong.httpclientutil.common.Utils; import com.arronlong.httpclientutil.exception.HttpProcessException; +import java.util.HashMap; +import java.util.Map; + /** * 上传功能测试 * @@ -33,7 +32,6 @@ public static void main(String[] args) throws HttpProcessException { .files(filePaths,"myfile",true)//.files(filePaths),如果服务器端有验证input 的name值,则请传递第二个参数,如果上传失败,则尝试第三个参数设置为true .map(map);//其他需要提交的参数 - Utils.debug();//开启打印日志,调用 Utils.debug(false);关闭打印日志 String r = HttpClientUtil.upload(config);//上传 System.out.println(r);