package com.yanzuoguang.util.helper; import com.yanzuoguang.util.exception.HttpCodeException; import com.yanzuoguang.util.thread.ProcessData; import com.yanzuoguang.util.thread.RunProcess; import com.yanzuoguang.util.vo.MapRow; import org.apache.commons.codec.Charsets; 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.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * HTTP请求工具类 * * @author 颜佐光 */ public class HttpHelper { /** * 链接超时 */ public static int HTTP_CONNECT_TIMEOUT = 3 * 1000; /** * 读取超时 */ public static int HTTP_READ_TIMEOUT = 12 * 1000; /** * 字符编码 */ public static final String CHARSET_DEFAULT = "UTF-8"; /** * 获取请求参数 * * @param obj 对象 * @return 返回地址 */ public static String getUrlParameter(Object obj) { return getUrlParameter(obj, "UTF-8"); } /** * 获取请求参数 * * @param obj 对象 * @return 请求参数字符串 */ public static String getUrlParameter(Object obj, String charset) { MapRow to = JsonHelper.to(obj, MapRow.class); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Object> kvp : to.entrySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(UrlHelper.encoding(kvp.getKey(), charset)); sb.append("="); sb.append(UrlHelper.encoding(StringHelper.toString(kvp.getValue()), charset)); } return sb.toString(); } /** * 获取连接 * * @param url 请求地址 * @return 链接 * @throws IOException 抛出的异常信息 */ public static HttpURLConnection getConn(String url) throws IOException { return getConn(url, null, false); } /** * 获取连接 * * @param url 请求地址 * @param header 请求头 * @return 链接 * @throws IOException 抛出的异常信息 */ public static HttpURLConnection getConn(String url, Map<String, String> header) throws IOException { return getConn(url, header, false); } /** * 获取连接 * * @param url 请求地址 * @param isApplicationJson 是否请求json * @return 链接 * @throws IOException 抛出的异常信息 */ public static HttpURLConnection getConn(String url, boolean isApplicationJson) throws IOException { return getConn(url, null, isApplicationJson); } /** * 获取连接 * * @param url 请求地址 * @param header 请求头 * @param isApplicationJson 是否请求json * @return 链接 * @throws IOException 抛出的异常信息 */ public static HttpURLConnection getConn(String url, Map<String, String> header, boolean isApplicationJson) throws IOException { // 创建URL对象 java.net.URL connUrl = new java.net.URL(url); // 打开URL连接 java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connUrl.openConnection(); // 设置通用属性 httpConn.setRequestProperty("Accept", "*/*"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); if (isApplicationJson) { httpConn.setRequestProperty("Content-Type", "application/json"); } // 处理自定义头 if (header != null) { for (Map.Entry<String, String> item : header.entrySet()) { httpConn.setRequestProperty(item.getKey(), item.getValue()); } } // 设置POST方式 httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.setConnectTimeout(HTTP_CONNECT_TIMEOUT); httpConn.setReadTimeout(HTTP_READ_TIMEOUT); return httpConn; } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param url 目的地址 * @param jsonString 请求参数,json字符串。 * @return 远程响应结果 */ public static String post(String url, String jsonString) { try { // 打开URL连接 java.net.HttpURLConnection httpConn = getConn(url); return post(httpConn, jsonString, CHARSET_DEFAULT); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param url 目的地址 * @return 远程响应结果 */ public static String get(String url) { return get(url, "UTF-8"); } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param url 目的地址 * @return 远程响应结果 */ public static String get(String url, String charset) { try { // 打开URL连接 java.net.HttpURLConnection httpConn = getConn(url); return get(httpConn, charset); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param url 目的地址 * @param jsonString 请求参数,json字符串。 * @return 远程响应结果 */ public static String postApplicationJSON(String url, String jsonString) { return postApplicationJSON(url, jsonString, "UTF-8"); } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param url 目的地址 * @param jsonString 请求参数,json字符串。 * @return 远程响应结果 */ public static String postApplicationJSON(String url, String jsonString, String charset) { try { // 打开URL连接 java.net.HttpURLConnection httpConn = getConn(url, true); return post(httpConn, jsonString, charset); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param httpConn 链接信息 * @param jsonString 请求参数,json字符串。 * @return 远程响应结果 */ public static String post(HttpURLConnection httpConn, String jsonString) throws IOException { return post(httpConn, jsonString, CHARSET_DEFAULT); } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param httpConn 链接信息 * @param jsonString 请求参数,json字符串。 * @param charset 输出编码 * @return 远程响应结果 */ public static String post(HttpURLConnection httpConn, String jsonString, String charset) throws IOException { httpConn.setRequestMethod("POST"); // 返回的结果 StringBuilder result = new StringBuilder(); // 读取响应输入流 BufferedReader in = null; PrintWriter out = null; // 处理请求参数 try { // 获取HttpURLConnection对象对应的输出流 out = new PrintWriter(httpConn.getOutputStream()); // 发送请求参数 out.write(jsonString); // flush输出流的缓冲 out.flush(); int returnCode = httpConn.getResponseCode(); if (returnCode == HttpURLConnection.HTTP_OK) { in = readStream(httpConn.getInputStream(), result, charset); } else { in = readStream(httpConn.getErrorStream(), result, charset); throw new HttpCodeException(StringHelper.toString(returnCode), StringHelper.getFirst(httpConn.getResponseMessage(), result.toString())); } } catch (HttpCodeException ex) { throw ex; } catch (Exception ex) { in = readStream(httpConn.getErrorStream(), result, charset); throw new HttpCodeException(StringHelper.toString(httpConn.getResponseCode()), ex.getMessage(), result.toString(), ex); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } return result.toString(); } /** * 发送POST请求,当请求失败时,抛出异常或返回空字符串 * * @param httpConn 链接信息 * @param jsonString 请求参数,json字符串。 * @return 远程响应结果 */ public static byte[] postResultByteArray(HttpURLConnection httpConn, String jsonString) throws IOException { // 返回的结果 byte[] byteArray; PrintWriter out = null; // 处理请求参数 String params = ""; try { params = jsonString; // 获取HttpURLConnection对象对应的输出流 out = new PrintWriter(httpConn.getOutputStream()); // 发送请求参数 out.write(params); // flush输出流的缓冲 out.flush(); int returnCode = httpConn.getResponseCode(); if (returnCode == HttpURLConnection.HTTP_OK) { byteArray = readByteArray(httpConn.getInputStream()); } else { throw new HttpCodeException(StringHelper.toString(returnCode), httpConn.getResponseMessage()); } } catch (HttpCodeException ex) { throw ex; } catch (Exception ex) { byteArray = readByteArray(httpConn.getErrorStream()); throw new HttpCodeException(StringHelper.toString(httpConn.getResponseCode()), ex.getMessage(), ex); } finally { if (out != null) { out.close(); } } return byteArray; } /** * 发送GET请求,当请求失败时,抛出异常或返回空字符串 * * @param httpConn 链接信息 * @return 远程响应结果 */ public static String get(HttpURLConnection httpConn) throws IOException { return get(httpConn, CHARSET_DEFAULT); } /** * 发送GET请求,当请求失败时,抛出异常或返回空字符串 * * @param httpConn 链接信息 * @return 远程响应结果 */ public static String get(HttpURLConnection httpConn, String charset) throws IOException { httpConn.setRequestMethod("GET"); // 返回的结果 StringBuilder result = new StringBuilder(); // 读取响应输入流 BufferedReader in = null; try { // 获取HttpURLConnection对象对应的输出流 in = readStream(httpConn.getInputStream(), result, charset); } catch (Exception ex) { in = readStream(httpConn.getErrorStream(), result, charset); throw new HttpCodeException(StringHelper.toString(httpConn.getResponseCode()), ex.getMessage(), result.toString(), ex); } finally { if (in != null) { in.close(); } } return result.toString(); } /** * 读取数据流 * * @param stream 流 * @param result 结果字符串 * @param charset 编码方式 * @return 读取的缓存流 * @throws IOException IO异常 */ private static BufferedReader readStream(InputStream stream, StringBuilder result, String charset) throws IOException { if (stream == null) { return null; } // 定义BufferedReader输入流来读取URL的响应,设置编码方式 BufferedReader in = new BufferedReader(new InputStreamReader(stream, charset)); String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result.append(line); } return in; } /** * 读取数据流 * * @param input 流 * @return 读取的缓存流 * @throws IOException IO异常 */ public static byte[] readByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } /** * 下载文件 * * @param serverFileName 下载的服务器文件路径 * @param localFileName 保存的文件路径 * @throws IOException IO异常 */ public static void downToLocal(String serverFileName, String localFileName) throws IOException { downToLocal(serverFileName, localFileName, null); } /** * 下载文件 * * @param serverFileName 下载的服务器文件路径 * @param localFileName 保存的文件路径 * @param runProcess 进度处理 * @throws IOException IO异常 */ public static void downToLocal(String serverFileName, String localFileName, RunProcess runProcess) throws IOException { int byteRead; URL url = new URL(serverFileName); URLConnection conn = url.openConnection(); conn.setConnectTimeout(HTTP_CONNECT_TIMEOUT); conn.setReadTimeout(HTTP_READ_TIMEOUT); try (InputStream inStream = conn.getInputStream()) { ProcessData data = new ProcessData(serverFileName, conn.getContentLengthLong()); try (FileOutputStream outputStream = new FileOutputStream(localFileName)) { byte[] buffer = new byte[1204]; while ((byteRead = inStream.read(buffer)) != -1) { data.processAdd(runProcess, byteRead); outputStream.write(buffer, 0, byteRead); } } } } /** * post请求form-data * * @param url 请求地址 * @param parametersBody 参数值 * @return 返回值 * @throws Exception 异常 */ public static String postRequest(String url, List<NameValuePair> parametersBody) throws Exception { HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8); return post(url, "application/x-www-form-urlencoded", entity); } private static String post(String url, String mediaType, HttpEntity entity) throws Exception { HttpPost post = new HttpPost(url); post.addHeader("Content-Type", mediaType); post.addHeader("Accept", "application/json"); post.setEntity(entity); RequestConfig config = RequestConfig.custom() .setConnectionRequestTimeout(HTTP_CONNECT_TIMEOUT) //建立socket链接超时 .setConnectTimeout(HTTP_CONNECT_TIMEOUT) //服务端相应超时 .setSocketTimeout(HTTP_READ_TIMEOUT) .build(); post.setConfig(config); String var8; try { HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); String result = EntityUtils.toString(response.getEntity()); if (code >= 400) { throw new HttpCodeException(String.valueOf(code), result); } var8 = result; } finally { post.releaseConnection(); } return var8; } }