http通信类的封装

简介: package sec.crm.sns.util; import java.io.BufferedInputStream; import java.io.

package sec.crm.sns.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import sec.crm.sns.wechat.vo.Attachment;

/**
 * https 请求 微信为https的请求
 */
public class HttpKit {
 private static final String DEFAULT_CHARSET = "UTF-8";
 private static final String _GET = "GET"; // GET
 private static final String _POST = "POST";// POST

 private static final Logger LOGGER = Logger.getLogger(HttpKit.class);

 public static String getIpAddr(HttpServletRequest request) {
  String ip = request.getHeader("x-forwarded-for");
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
   ip = request.getHeader("Proxy-Client-IP");
  }
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
   ip = request.getHeader("WL-Proxy-Client-IP");
  }
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
   ip = request.getRemoteAddr();
  }
  if (ip.equals("127.0.0.1")) {
   // 根据网卡取本机配置的IP
   InetAddress inet = null;
   try {
    inet = InetAddress.getLocalHost();
   } catch (Exception e) {
    return "*.*.*.*";
   }
   ip = inet.getHostAddress();
  }
  // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  if (ip != null && ip.length() > 15) { // "***.***.***.***".length()
   // = 15
   if (ip.indexOf(",") > 0) {
    ip = ip.substring(0, ip.indexOf(","));
   }
  }
  return ip;
 }

 /**
  * 初始化http请求参数
  *
  * @param url
  * @param method
  * @param headers
  * @return
  * @throws IOException
  */
 private static HttpURLConnection initHttp(String url, String method,
   Map<String, String> headers) throws IOException {
  URL _url = new URL(url);
  HttpURLConnection http = (HttpURLConnection) _url.openConnection();
  // 连接超时
  http.setConnectTimeout(25000);
  // 读取超时 --服务器响应比较慢,增大时间
  http.setReadTimeout(25000);
  http.setRequestMethod(method);
  http.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  http.setRequestProperty(
    "User-Agent",
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
  if (null != headers && !headers.isEmpty()) {
   for (Entry<String, String> entry : headers.entrySet()) {
    http.setRequestProperty(entry.getKey(), entry.getValue());
   }
  }
  http.setDoOutput(true);
  http.setDoInput(true);
  http.connect();
  return http;
 }

 /**
  * 初始化http请求参数
  *
  * @param url
  * @param method
  * @return
  * @throws IOException
  * @throws NoSuchAlgorithmException
  * @throws NoSuchProviderException
  * @throws KeyManagementException
  */
 private static HttpsURLConnection initHttps(String url, String method,
   Map<String, String> headers) throws IOException,
   NoSuchAlgorithmException, NoSuchProviderException,
   KeyManagementException {
  TrustManager[] tm = { new MyX509TrustManager() };
  SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  sslContext.init(null, tm, new java.security.SecureRandom());
  // 从上述SSLContext对象中得到SSLSocketFactory对象
  SSLSocketFactory ssf = sslContext.getSocketFactory();
  URL _url = new URL(url);
  HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
  // 设置域名校验
  http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
  // 连接超时
  http.setConnectTimeout(25000);
  // 读取超时 --服务器响应比较慢,增大时间
  http.setReadTimeout(25000);
  http.setRequestMethod(method);
  http.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  http.setRequestProperty(
    "User-Agent",
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
  if (null != headers && !headers.isEmpty()) {
   for (Entry<String, String> entry : headers.entrySet()) {
    http.setRequestProperty(entry.getKey(), entry.getValue());
   }
  }
  http.setSSLSocketFactory(ssf);
  http.setDoOutput(true);
  http.setDoInput(true);
  http.connect();
  return http;
 }

 /**
  *
  * @description 功能描述: get 请求
  * @return 返回类型:
  * @throws IOException
  * @throws UnsupportedEncodingException
  * @throws NoSuchProviderException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  */
 public static String get(String url, Map<String, String> params,
   Map<String, String> headers) throws KeyManagementException,
   NoSuchAlgorithmException, NoSuchProviderException,
   UnsupportedEncodingException, IOException {
  HttpURLConnection http = null;
  if (isHttps(url)) {
   http = initHttps(initParams(url, params), _GET, headers);
  } else {
   http = initHttp(initParams(url, params), _GET, headers);
  }
  InputStream in = http.getInputStream();
  BufferedReader read = new BufferedReader(new InputStreamReader(in,
    DEFAULT_CHARSET));
  String valueString = null;
  StringBuffer bufferRes = new StringBuffer();
  while ((valueString = read.readLine()) != null) {
   bufferRes.append(valueString);
  }
  in.close();
  if (http != null) {
   http.disconnect();// 关闭连接
  }
  return bufferRes.toString();
 }

 /**
  *
  * @description 功能描述: get 请求
  * @return 返回类型:
  * @throws IOException
  * @throws UnsupportedEncodingException
  * @throws NoSuchProviderException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  */
 public static String get(String url) throws KeyManagementException,
   NoSuchAlgorithmException, NoSuchProviderException,
   UnsupportedEncodingException, IOException {
  return get(url, null);
 }

 /**
  *
  * @description 功能描述: get 请求
  * @return 返回类型:
  * @throws IOException
  * @throws NoSuchProviderException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  * @throws UnsupportedEncodingException
  */
 public static String get(String url, Map<String, String> params)
   throws KeyManagementException, NoSuchAlgorithmException,
   NoSuchProviderException, UnsupportedEncodingException, IOException {
  return get(url, params, null);
 }

 /**
  * @description 功能描述: POST 请求
  * @return 返回类型:
  * @throws IOException
  * @throws NoSuchProviderException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  */
 public static String post(String url, String params)
   throws KeyManagementException, NoSuchAlgorithmException,
   NoSuchProviderException, IOException {
  HttpURLConnection http = null;
  if (isHttps(url)) {
   http = initHttps(url, _POST, null);
  } else {
   http = initHttp(url, _POST, null);
  }
  OutputStream out = http.getOutputStream();
  out.write(params.getBytes(DEFAULT_CHARSET));
  out.flush();
  out.close();
  InputStream in = http.getInputStream();
  BufferedReader read = new BufferedReader(new InputStreamReader(in,
    DEFAULT_CHARSET));
  String valueString = null;
  StringBuffer bufferRes = new StringBuffer();
  while ((valueString = read.readLine()) != null) {
   bufferRes.append(valueString);
  }
  in.close();
  if (http != null) {
   http.disconnect();// 关闭连接
  }
  return bufferRes.toString();
 }

 /**
  * 上传媒体文件
  *
  * @param url
  * @param params
  * @param file
  * @return
  * @throws IOException
  * @throws NoSuchAlgorithmException
  * @throws NoSuchProviderException
  * @throws KeyManagementException
  */
 public static String upload(String url, File file) throws IOException,
   NoSuchAlgorithmException, NoSuchProviderException,
   KeyManagementException {
  String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // 定义数据分隔线
  StringBuffer bufferRes = null;
  URL urlGet = new URL(url);
  HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setUseCaches(false);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("connection", "Keep-Alive");
  conn.setRequestProperty(
    "user-agent",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
  conn.setRequestProperty("Charsert", "UTF-8");
  conn.setRequestProperty("Content-Type",
    "multipart/form-data; boundary=" + BOUNDARY);
  OutputStream out = new DataOutputStream(conn.getOutputStream());
  byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
  StringBuilder sb = new StringBuilder();
  sb.append("--");
  sb.append(BOUNDARY);
  sb.append("\r\n");
  sb.append("Content-Disposition: form-data;name=\"media\";filename=\""
    + file.getName() + "\"\r\n");
  sb.append("Content-Type:application/octet-stream\r\n\r\n");
  byte[] data = sb.toString().getBytes();
  out.write(data);
  DataInputStream fs = new DataInputStream(new FileInputStream(file));
  int bytes = 0;
  byte[] bufferOut = new byte[1024];
  while ((bytes = fs.read(bufferOut)) != -1) {
   out.write(bufferOut, 0, bytes);
  }
  out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
  fs.close();
  out.write(end_data);
  out.flush();
  out.close();
  // 定义BufferedReader输入流来读取URL的响应
  InputStream in = conn.getInputStream();
  BufferedReader read = new BufferedReader(new InputStreamReader(in,
    DEFAULT_CHARSET));
  String valueString = null;
  bufferRes = new StringBuffer();
  while ((valueString = read.readLine()) != null) {
   bufferRes.append(valueString);
  }
  in.close();
  if (conn != null) {
   // 关闭连接
   conn.disconnect();
  }
  return bufferRes.toString();
 }

 /**
  * 下载资源
  *
  * @param url
  * @return
  * @throws IOException
  */
 public static Attachment download(String url) throws IOException {
  Attachment att = new Attachment();
  HttpURLConnection conn = initHttp(url, _GET, null);
  if (conn.getContentType().equalsIgnoreCase("text/plain")) {
   // 定义BufferedReader输入流来读取URL的响应
   InputStream in = conn.getInputStream();
   BufferedReader read = new BufferedReader(new InputStreamReader(in,
     DEFAULT_CHARSET));
   String valueString = null;
   StringBuffer bufferRes = new StringBuffer();
   while ((valueString = read.readLine()) != null) {
    bufferRes.append(valueString);
   }
   in.close();
   att.setError(bufferRes.toString());
  } else {
   BufferedInputStream bis = new BufferedInputStream(
     conn.getInputStream());
   String ds = conn.getHeaderField("Content-disposition");
   String fullName = ds.substring(ds.indexOf("filename=\"") + 10,
     ds.length() - 1);
   String relName = fullName.substring(0, fullName.lastIndexOf("."));
   String suffix = fullName.substring(relName.length() + 1);
   att.setFullName(fullName);
   att.setFileName(relName);
   att.setSuffix(suffix);
   att.setContentLength(conn.getHeaderField("Content-Length"));
   att.setContentType(conn.getHeaderField("Content-Type"));
   att.setFileStream(bis);
  }
  return att;
 }

 /**
  * 功能描述: 构造请求参数
  *
  * @return 返回类型:
  * @throws UnsupportedEncodingException
  */
 public static String initParams(String url, Map<String, String> params)
   throws UnsupportedEncodingException {
  if (null == params || params.isEmpty()) {
   return url;
  }
  StringBuilder sb = new StringBuilder(url);
  if (url.indexOf("?") == -1) {
   sb.append("?");
  }
  sb.append(map2Url(params));
  return sb.toString();
 }

 /**
  * map构造url
  *
  * @return 返回类型:
  * @throws UnsupportedEncodingException
  */
 public static String map2Url(Map<String, String> paramToMap)
   throws UnsupportedEncodingException {
  if (null == paramToMap || paramToMap.isEmpty()) {
   return null;
  }
  StringBuffer url = new StringBuffer();
  boolean isfist = true;
  for (Entry<String, String> entry : paramToMap.entrySet()) {
   if (isfist) {
    isfist = false;
   } else {
    url.append("&");
   }
   url.append(entry.getKey()).append("=");
   String value = entry.getValue();
   if (StringUtils.isNotEmpty(value)) {
    url.append(URLEncoder.encode(value, DEFAULT_CHARSET));
   }
  }
  return url.toString();
 }

 /**
  * 检测是否https
  *
  * @param url
  */
 private static boolean isHttps(String url) {
  return url.startsWith("https");
 }

 /**
  * https 域名校验
  *
  * @param url
  * @param params
  * @return
  */
 public class TrustAnyHostnameVerifier implements HostnameVerifier {
  public boolean verify(String hostname, SSLSession session) {
   return true;// 直接返回true
  }
 }

 public static void main(String[] args) {
  String fname = "dsasdas.mp4";
  String s = fname.substring(0, fname.lastIndexOf("."));
  String f = fname.substring(s.length() + 1);
  System.out.println(f);
 }
}

/**
 * 证书管理
 */
class MyX509TrustManager implements X509TrustManager {
 public X509Certificate[] getAcceptedIssuers() {
  return null;
 }

 @Override
 public void checkClientTrusted(X509Certificate[] chain, String authType)
   throws CertificateException {
 }

 @Override
 public void checkServerTrusted(X509Certificate[] chain, String authType)
   throws CertificateException {
 }
}

目录
相关文章
|
Android开发
Android Http 请求封装及使用
Android Http 请求封装及使用
232 0
|
23天前
|
缓存
HTTP 报文解构:深入剖析 HTTP 通信的核心要素
【10月更文挑战第21天】随着网络技术的不断发展和演进,HTTP 报文的形式和功能也可能会发生变化,但对其基本解构的理解始终是掌握 HTTP 通信的关键所在。无论是在传统的 Web 应用中,还是在新兴的网络技术领域,对 HTTP 报文的深入认识都将为我们带来更多的机遇和挑战。
|
7月前
|
JSON Java 数据安全/隐私保护
java中的http请求的封装(GET、POST、form表单、JSON形式、SIGN加密形式)
java中的http请求的封装(GET、POST、form表单、JSON形式、SIGN加密形式)
532 1
|
5月前
|
JSON Dart API
Flutter dio http 封装指南说明
本文介绍了如何实现一个通用、可重构的 Dio 基础类,包括单例访问、日志记录、常见操作封装以及请求、输出、报错拦截等功能。
117 2
Flutter dio http 封装指南说明
|
4月前
|
负载均衡 Java API
深度解析SpringCloud微服务跨域联动:RestTemplate如何驾驭HTTP请求,打造无缝远程通信桥梁
【8月更文挑战第3天】踏入Spring Cloud的微服务世界,服务间的通信至关重要。RestTemplate作为Spring框架的同步客户端工具,以其简便性成为HTTP通信的首选。本文将介绍如何在Spring Cloud环境中运用RestTemplate实现跨服务调用,从配置到实战代码,再到注意事项如错误处理、服务发现与负载均衡策略,帮助你构建高效稳定的微服务系统。
95 2
|
5月前
|
Java Spring
spring restTemplate 进行http请求的工具类封装
spring restTemplate 进行http请求的工具类封装
224 3
|
5月前
|
存储 网络安全 数据安全/隐私保护
[flask]使用mTLS双向加密认证http通信
【7月更文挑战第16天】在Flask应用中实现mTLS双向TLS加密认证可增强HTTP通信安全性。步骤包括: 1. 使用OpenSSL为服务器和客户端生成证书和密钥。 2. 配置Flask服务器使用这些证书: - 安装`flask`和`pyopenssl`. - 设置SSL上下文并启用mTLS验证: 注意事项: - 保持证书有效期并及时更新. - 确保证书链信任. - 充分测试mTLS配置.
100 2
|
5月前
|
消息中间件 API 数据库
在微服务架构中,每个服务通常都是一个独立运行、独立部署、独立扩展的组件,它们之间通过轻量级的通信机制(如HTTP/RESTful API、gRPC等)进行通信。
在微服务架构中,每个服务通常都是一个独立运行、独立部署、独立扩展的组件,它们之间通过轻量级的通信机制(如HTTP/RESTful API、gRPC等)进行通信。
|
4月前
|
安全 网络安全 数据安全/隐私保护
[flask]使用mTLS双向加密认证http通信
[flask]使用mTLS双向加密认证http通信
112 0
|
4月前
|
网络协议 应用服务中间件 Go
[golang]使用mTLS双向加密认证http通信
[golang]使用mTLS双向加密认证http通信

热门文章

最新文章