package com.hxzkmonitor.util; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { final static int TIMEOUT = 1000; final static int TIMEOUT_MSEC = 5 * 1000; /** * Http get请求 * @param httpUrl 连接 * @return 响应数据 */ public static String doGet(String httpUrl){ //链接 HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; StringBuffer result = new StringBuffer(); try { //创建连接 URL url = new URL(httpUrl); connection = (HttpURLConnection) url.openConnection(); //设置请求方式 connection.setRequestMethod("GET"); //设置连接超时时间 connection.setReadTimeout(15000); //开始连接 connection.connect(); //获取响应数据 if (connection.getResponseCode() == 200) { //获取返回的数据 is = connection.getInputStream(); if (null != is) { br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String temp = null; while (null != (temp = br.readLine())) { result.append(temp); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } //关闭远程连接 connection.disconnect(); } return result.toString(); } public static String doPost(String url, Map paramMap) throws IOException { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //创建响应对象 CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (paramMap != null) { List paramList = new ArrayList<>(); for (Map.Entry param : paramMap.entrySet()) { paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } httpPost.setConfig(builderRequestConfig()); // 执行请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { throw new IOException("HttpClientUtil工具类执行请求失败---" + e); } finally { try { response.close(); } catch (IOException e) { throw new IOException("HttpClientUtil工具类关闭响应资源失败---" + e); } } return resultString; } public static String doPost1(String url, Map paramMap) throws IOException { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //创建响应对象 CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (paramMap != null) { List paramList = new ArrayList<>(); for (Map.Entry param : paramMap.entrySet()) { paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } httpPost.setConfig(builderRequestConfig()); // 执行请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { throw new IOException("HttpClientUtil工具类执行请求失败---" + e); } finally { try { response.close(); } catch (IOException e) { throw new IOException("HttpClientUtil工具类关闭响应资源失败---" + e); } } return resultString; } public static String doPostFile2(String url) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 处理https链接 if (url.startsWith("https://")) { httpClient = sslClient(); } String resultString = ""; CloseableHttpResponse response = null; HttpPost httppost = new HttpPost(url); try { // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码 MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); // 设置请求的编码格式 builder.setCharset(Consts.UTF_8); builder.setContentType(ContentType.MULTIPART_FORM_DATA); // 添加文件,也可以添加字节流 // builder.addBinaryBody("file", file); //或者使用字节流也行,根据具体需要使用 // builder.addBinaryBody("file", Files.readAllBytes(file.toPath()),ContentType.APPLICATION_OCTET_STREAM,file.getName()); // // 或者builder.addPart("file",new FileBody(file)); // // 添加参数 // if (param != null) { // for (String key : param.keySet()) { // builder.addTextBody(key, param.get(key)); // } // } //httppost.addHeader("token", param.get("token")); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); // 设置超时时间 httppost.setConfig(getConfig()); response = httpClient.execute(httppost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } private static RequestConfig getConfig() { return RequestConfig.custom().setConnectionRequestTimeout(60000).setSocketTimeout(120000) .setConnectTimeout(60000).build(); } private static CloseableHttpClient sslClient() { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } } public static void sendPostRequestWithImage(String targetUrl, File imageFile) throws IOException { String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界 String CRLF = "\r\n"; // 换行符 URL url = new URL(targetUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); ) { // 发送文件数据 writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"" + imageFile.getName() + "\"").append(CRLF); writer.append("Content-Type: image/jpeg").append(CRLF); // 假设是jpeg格式 writer.append(CRLF).flush(); try (InputStream inputStream = new FileInputStream(imageFile)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } output.flush(); // 确保图片数据完全写出 } // 结束边界 writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); } int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); connection.disconnect(); } private static RequestConfig builderRequestConfig() { return RequestConfig.custom() .setConnectTimeout(TIMEOUT_MSEC) .setConnectionRequestTimeout(TIMEOUT_MSEC) .setSocketTimeout(TIMEOUT_MSEC).build(); } }