http通訊類的封裝
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 {
}
}
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750077/viewspace-2108806/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 網路通訊1:位元組流的封裝封裝
- netty系列之:netty對http2訊息的封裝NettyHTTP封裝
- 一、類的封裝性封裝
- 使用APICloud AVM框架封裝通訊錄元件APICloud框架封裝元件
- php用curl封裝一個http請求類(鏈式呼叫)PHP封裝HTTP
- 十五、類與封裝的概念封裝
- Jaeger TChannel——HTTP和JSON封裝HTTPJSON封裝
- 通過Handler封裝的網路請求資料的工具類NetUtils封裝
- 封裝Date工具類封裝
- 封裝Redis工具類封裝Redis
- HTTP協議的通訊框架HTTP協議框架
- [譯]axios 是如何封裝 HTTP 請求的iOS封裝HTTP
- HTTP通訊協議HTTP協議
- c#封裝DBHelper類C#封裝
- 4、類和物件—封裝物件封裝
- 自用驗證類封裝封裝
- Android常用工具類的封裝Android封裝
- 基於javascript的拖拽類封裝^o^JavaScript封裝
- 簡訊介面封裝封裝
- Angular6筆記之封裝httpAngular筆記封裝HTTP
- Flutter Dio http簡單封裝與使用FlutterHTTP封裝
- eventBus(封裝) 一個巧妙的解決vue同級元件通訊的思路封裝Vue元件
- 通訊工具類
- Android之Activity基類封裝Android封裝
- c# Lambda操作類封裝C#封裝
- Tcp, WebSocket 和 http 之間的通訊TCPWebHTTP
- 【JavaScript框架封裝】實現一個類似於JQuery的動畫框架的封裝JavaScript框架封裝jQuery動畫
- 5.Hibernate工具類的簡易封裝封裝
- 深度解密HTTP通訊細節解密HTTP
- 如何使用Flutter封裝即時通訊IM框架開發外掛Flutter封裝框架
- 【JavaScript框架封裝】實現一個類似於JQuery的CSS樣式框架的封裝JavaScript框架封裝jQueryCSS
- 靜態庫封裝之ComStr類封裝
- 靜態庫封裝之ComFile類封裝
- 靜態庫封裝之ComDir類封裝
- 一次Android動畫工具類的封裝Android動畫封裝
- 一個完整的COM通訊類
- Java類的設計和封裝及類成員的訪問控制Java封裝
- 封裝狀態資訊碼封裝
- QT使用 http 協議通訊的實現示例QTHTTP協議