springboot的IT技术交流和分享平台的设计与实现042
开发工具:idea 或eclipse
数据库mysql5.7+
数据库链接工具:navcat,小海豚等
package com.wuye.util;
import com.alibaba.fastjson.JSONObject;
import com.wuye.config.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
/**
* @author hb
* @date 2022-03-01 10:30
*/
@Slf4j
public class HttpsUtil {
/**
* 鍙戦�乭ttps璇锋眰
*
* @param requestUrl 璇锋眰鍦板潃
* @param requestMethod 璇锋眰鏂瑰紡锛圙ET銆丳OST锛�
* @param outputStr 鎻愪氦鐨勬暟鎹�
* @return JSONObject(閫氳繃JSONObject.get(key)鐨勬柟寮忚幏鍙杍son瀵硅薄鐨勫睘鎬у��)
*/
public static JSONObject
httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 鍒涘缓SSLContext瀵硅薄锛屽苟浣跨敤鎴戜滑鎸囧畾鐨勪俊浠荤鐞嗗櫒鍒濆鍖�
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 璁剧疆璇锋眰鏂瑰紡锛圙ET/POST锛�
conn.setRequestMethod(requestMethod);
// 褰搊utputStr涓嶄负null鏃跺悜杈撳嚭娴佸啓鏁版嵁
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 娉ㄦ剰缂栫爜鏍煎紡
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 浠庤緭鍏ユ祦璇诲彇杩斿洖鍐呭
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 閲婃斁璧勬簮
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (Exception e) {
}
return jsonObject;
}
public static String getIp(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String forwarded = request.getHeader("X-Forwarded-For");
String realIp = request.getHeader("X-Real-IP");
String ip = null;
if (realIp == null) {
if (forwarded == null) {
ip = remoteAddr;
} else {
ip = remoteAddr + "/" + forwarded;
}
} else {
if (realIp.equals(forwarded)) {
ip = realIp;
} else {
ip = realIp + "/" + forwarded.replaceAll(", " + realIp, "");
}
}
return ip;
}
public static String connectHttpsByPost(String path, String KK, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
URL urlObj = new URL(path);
//閾炬帴
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
String result = null;
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post鏂瑰紡涓嶈兘浣跨敤缂撳瓨
// 璁剧疆璇锋眰澶翠俊鎭�
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 璁剧疆杈圭晫
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type",
"multipart/form-data; boundary="
+ BOUNDARY);
// 璇锋眰姝f枃淇℃伅
// 绗竴閮ㄥ垎锛�
StringBuilder sb = new StringBuilder();
sb.append("--"); // 蹇呴』澶氫袱閬撶嚎
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 寰楀埌杈撳嚭娴�
OutputStream out = new DataOutputStream(con.getOutputStream());
// 杈撳嚭琛ㄥご
out.write(head);
// 鏂囦欢姝f枃閮ㄥ垎
// 鎶婃枃浠跺凡娴佹枃浠剁殑鏂瑰紡 鎺ㄥ叆鍒皍rl涓�
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 缁撳熬閮ㄥ垎
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 瀹氫箟鏈�鍚庢暟鎹垎闅旂嚎
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
// 瀹氫箟BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴�
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("鍙戦�丳OST璇锋眰鍑虹幇寮傚父锛�" + e);
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
return result;
}
/**
* 涓婁紶鍏朵綑姘镐箙绱犳潗(鍥剧墖绱犳潗鐨勪笂闄愪负5000锛屽叾浣欑被鍨嬩负1000)
*
* @return
* @throws Exception
*/
public static JSONObject addMaterialEver(File file, String type, String token) {
try {
//涓婁紶绱犳潗
String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type=" + type;
String result = connectHttpsByPost(path, null, file);
result = result.replaceAll("[\\\\]", "");
System.out.println("result:" + result);
JSONObject resultJSON = JSONObject.parseObject(result);
return resultJSON;
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
public static String doPost(String strHttpsUrl, String jsonString) {
String result = null;
try {
DataOutputStream output = null;
BufferedReader reader = null;
HttpsURLConnection httpConnnect = null;
try {
//鍒涘缓杩炴帴
URL httpUrl = new URL(strHttpsUrl);
httpConnnect = (HttpsURLConnection) httpUrl.openConnection();
//璁剧疆杩炴帴灞炴��
httpConnnect.setDoOutput(true); //杈撳嚭(鍙戦�佹暟鎹�)
httpConnnect.setDoInput(true); //杈撳叆(鎺ユ敹鏁版嵁)
httpConnnect.setRequestMethod("POST"); //璁剧疆璇锋眰鏂瑰紡
httpConnnect.setUseCaches(false); //璁剧疆鏄惁寮�鍚紦瀛橈紝post璇锋眰鏃讹紝缂撳瓨蹇呴』鍏虫帀
httpConnnect.setInstanceFollowRedirects(true); //璁剧疆杩炴帴鏄惁鑷姩澶勭悊閲嶅畾鍚戯紙setFollowRedirects锛氭墍鐢╤ttp杩炴帴锛泂etInstanceFollowRedirects锛氭湰娆¤繛鎺ワ級
httpConnnect.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); //璁剧疆鎻愪氦鍐呭绫诲瀷(璁剧疆璇锋眰澶�)
//寮�濮嬭繛鎺�
httpConnnect.connect();
//鍙戦�佽姹�
output = new DataOutputStream(httpConnnect.getOutputStream());
//鍙戦��
if (StringUtils.isNotBlank(jsonString)) {
output.write(jsonString.getBytes("UTF-8"));
}
output.flush();
output.close();
//璇诲彇鍝嶅簲
reader = new BufferedReader(new InputStreamReader(httpConnnect.getInputStream(), "UTF-8"));
String lines;
StringBuffer stringBuffer = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes());
stringBuffer.append(lines);
}
result = stringBuffer.toString();
log.info("[doPost] 杩斿洖缁撴灉锛�" + result);
reader.close();
// 鏂紑杩炴帴
httpConnnect.disconnect();
} catch (Exception e) {
e.printStackTrace();
log.error("[doPost] 鍙戦�乸ost 璇锋眰澶辫触: {}", e.getMessage());
} finally {
if (output != null) {
output.flush();
output.close();
}
if (reader != null) {
reader.close();
}
if (httpConnnect != null) {
httpConnnect.disconnect();
}
}
} catch (Exception e) {
log.error("[doPost] 鍙戦�乸ost 璇锋眰澶辫触: {}", e.getMessage());
}
return result;
}
}