package com.gym.rule.vo;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
* Create on 2021/11/15.
*
* @author Jaime
* @Description :
* net.sf.json.JSONObject result = ConnectedUtil.getConnection(basicRemoteUrl + "/remotePta/reportCallBack", map);
*/
public class ConnectedUtil {
static final Logger logger = LoggerFactory.getLogger(ConnectedUtil.class);
//获取连接的方法
public static JSONObject getConnection(String URL, Map<String, Object> map) throws Exception {
String result = "";
// 建立连接
//http(测试和本地)
// java.net.URL url = new URL(URL);
// HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//https(正式环境)
URL url= new URL(null, URL, new sun.net.www.protocol.https.Handler());
logger.info("访问的路径为==>" + url);
HttpsURLConnection httpConn = (HttpsURLConnection) url.openConnection();
// 设置参数
httpConn.setDoOutput(true); // 需要输出
httpConn.setDoInput(true); // 需要输入
httpConn.setUseCaches(false); // 不允许缓存
httpConn.setRequestMethod("POST");// 设置POST方式连接
// 设置请求属性
httpConn.setRequestProperty("Content-Type","application/json");
httpConn.setRequestProperty("Connection","Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset","UTF-8");
//https时才配置
httpConn.setHostnameVerifier(new ConnectedUtil().new TrustAnyHostnameVerifier());
// 连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
httpConn.connect();
JSONObject jsonObject = JSONObject.fromObject(map);
// 建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
dos.write(jsonObject.toString().getBytes("UTF-8"));
dos.flush();
dos.close();
// 获得响应状态
JSONObject jsonmsg = null;
BufferedReader in = null;
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
// 解析json对象
jsonmsg = JSONObject.fromObject(result);
}
return jsonmsg;
}
// 定製Verifier
public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
远程连接传输
于 2022-02-16 17:22:39 首次发布