package com.commercial.formats.utils;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONObject;
import javax.net.ssl.*;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import static com.commercial.formats.utils.SendCodeUtils.sendPost;
public class HttpRequestUtil {
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
StringBuffer buffer = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
conn.connect();
//往服务器端写内容 也就是发起http请求需要带的参数
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() == 200) {
if (null != outputStr) {
OutputStream os = conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args) {
// String str = "{"appSecret":"9b0db5224618495886cd5ce8e83b33e6"}";
// //String s = sendPost("https://test-api.lejian.com/open-api/V2/accesstoken?appKey=apc0a9fb5a2f024a2493ae47ae7ab22215",str);
// String s = sendPostHttps("https://test-api.lejian.com/open-api/V2/nonce?accessToken=3Yu3yOtTOno5Aqxigoar0XlZdoqOt-QoACfGl8v5ZUVz08K76WVZa8aP6_ALXiCvrHMODQm9h2M19GUarzxQ224_uS6ZzF3ymmDCRnx4aHVnrlCrYLnq2cf5Jy3_Gda2n-5gYqs5f59qtbbSIYOMTb8SSTIJ2_zXYSpYQo",null);
// //String s = httpRequest("https://test-api.lejian.com/open-api/V2/accesstoken?appKey=apc0a9fb5a2f024a2493ae47ae7ab22215", "POST", str);
//
//
// String sd = sendPostHttps("https://test-api.lejian.com/open-api/V2/accesstoken?appKey=apc0a9fb5a2f024a2493ae47ae7ab22215", str);
//
// JSONObject parse = JSONObject.parseObject(sendPost("https://test-api.lejian.com/open-api/V2/accesstoken?appKey=apc0a9fb5a2f024a2493ae47ae7ab22215", str));
//
// System.out.println(parse.getString("accessToken"));
SortedMap<String, String> params = new TreeMap<String, String>();
params.put("appid", "SKY_56E796FD46904926");
params.put("projectnumber", "wy-tjlsq");
params.put("appsecret", "ca41f2335d3343208a1240a7aa70e427");
params.put("timestamp", "1610335508");
StringBuilder str = new StringBuilder("");
for (Map.Entry<String, String> entry : params.entrySet()) {
str.append(entry.getKey()+"="+entry.getValue()+"&");
}
System.out.println(str);
String str2 = str.toString().substring(0,str.length()-1);
System.out.println(str2);
System.out.println(stringToMD5(str2));
// System.out.println(stringToMD5("appid=SKY_5F5D3A8633287806&appsecret=631814edbf044f2db9cb810d0fdfaa73&mobilephone=13012345678×tamp=1610335508"));
}
public static void StringToAscii(){//字符串转换为ASCII码
String s="appid=SKY_5F5D3A8633287806×tamp=1610335508&mobilephone=13012345678";//字符串
char[]chars=s.toCharArray(); //把字符中转换为字符数组
System.out.println("STRING TO ASCII
----------------------");
for(int i=0;i<chars.length;i++)
{
System.out.println(chars[i]+" "+(int)chars[i]);
}
}
public static String stringToMD5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有这个md5算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
public static String sendPostHttps(String url,String param){
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
// 打开和URL之间的连接
URL realUrl = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
conn.setSSLSocketFactory(ssf);
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("content-Type", "application/json");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println("-----result-----"+result);
} catch (Exception e) {
e.printStackTrace();
} finally {// 使用finally块来关闭输出流、输入流
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
//添加主机名验证程序类,设置不验证主机
private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
//添加信任主机
private static void trustAllHosts() {
// 创建不验证证书链的信任管理器 这里使用的是x509证书
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
// 安装所有信任的信任管理器
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接,SSLSocket对象是由SSLSocketFactory生成的。
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
public static String sendPostHttpsByUrlencoded(String urls, String param, String contentType, String method) {
StringBuffer sb=new StringBuffer();
DataOutputStream out = null;
BufferedReader responseReader = null;
InputStream in1 = null;
try {
trustAllHosts();
// 创建url资源
URL url = new URL(urls);
// 建立http连接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
// 设置不用缓存
conn.setUseCaches(false);
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置传递方式
conn.setRequestMethod(method);
System.out.println(conn.getRequestMethod());
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
// byte[] data = (param).getBytes();
// // 设置文件长度
// conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("Content-Type", contentType);
// 开始连接请求
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
// 写入请求的字符串
out.writeBytes(param);
out.flush();
System.out.println(conn.getResponseCode());
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
System.out.println("连接成功");
// 请求返回的数据
in1 = conn.getInputStream();
String readLine;
responseReader = new BufferedReader(new InputStreamReader(in1,"UTF-8"));
while((readLine=responseReader.readLine()) != null){
sb.append(readLine).append("
");
}
} else {
System.out.println("error++");
}
} catch (Exception e) {
} finally {
try {
if (null != responseReader)
responseReader.close();
if (null != in1)
in1.close();
} catch(Exception e) {}
try {
out.close();
} catch(Exception e) {}
}
return sb.toString();
}
/**
* map转url参数
*/
public static String map2Url(Map<String, String> paramToMap) {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue();
if (!StringUtils.isEmpty(value)) {
try {
url.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return url.toString();
}
//测试
String sign = getSign(projectNumber);
Map<String, String> params = new HashMap<>();
params.put("appid", appid);
params.put("projectnumber", projectNumber);
params.put("sign",sign);
params.put("timestamp", timestamp);
JSONObject parse = JSONObject.parseObject(sendPostHttpsByUrlencoded(urls, map2Url(params), "application/x-www-form-urlencoded;charset=UTF-8", "POST"));
}