HttpsUtil 跳过ssl认证公用方法(兼容骨灰项目低版本)
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.rmi.ConnectException;
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 org.dom4j.DocumentException;
import com.payment.entity.LogEntity;
import net.sf.json.JSONObject;
public class HttpsUtils1 {
private static final LogEntity logger = new LogEntity("ott_payment");
static ThreadLocal<Integer> tLocal = new ThreadLocal<>();
static int MAX_REQUEST = 0;
private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslsession) {
System.out.println("WARNING: Hostname is not matched for cert.");
return true;
}
};
public static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static void download(String urlStr, File file) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
InputStream is = connection.getInputStream();
byte[] buffer = new byte[8*1024];
file.getParentFile().mkdirs();
FileOutputStream fileout = new FileOutputStream(file);
int len;
try {
while ((len = is.read(buffer))!=-1) {
fileout.write(buffer, 0, len);
}
fileout.flush();
fileout.getFD().sync();
} finally {
if(fileout!=null){
fileout.close();
}
if(is!=null){
is.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getResult(String urlStr,String charset) {
URL url = null;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null!=reader){
try {
reader.close();
} catch (IOException e) {
}
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
public static String getResultNotReTry(String urlStr,String charset) {
URL url = null;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (IOException e) {
if (e.getMessage().contains("Read timed out")) {
MAX_REQUEST++;
if (MAX_REQUEST <= 3) {
System.out.println("Try to connect again: " + MAX_REQUEST);
getResult(urlStr,charset);
}
MAX_REQUEST = 0;
}
e.printStackTrace();
} finally {
if(null!=reader){
try {
reader.close();
} catch (IOException e) {
}
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
public static String sendGet(String urlNameString) {
long start = System.currentTimeMillis();
logger.warn("---sendGet:"+urlNameString);
StringBuffer result = new StringBuffer("");
BufferedReader in = null;
HttpURLConnection connection = null;
try {
URL realUrl = new URL(urlNameString);
connection = (HttpURLConnection) realUrl.openConnection();
connection.connect();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
logger.warn("---sendGet costs:"+(System.currentTimeMillis()-start));
return result.toString();
}
public static String sendPost(String url, String param) {
long start = System.currentTimeMillis();
logger.warn("---sendPost:"+url);
PrintWriter out = null;
BufferedReader in = null;
StringBuffer result = new StringBuffer("");
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
logger.warn("---sendPost costs:"+(System.currentTimeMillis()-start));
return result.toString();
}
public static String doPost2(String url, String param) {
long start = System.currentTimeMillis();
PrintWriter out = null;
BufferedReader in = null;
StringBuffer result = new StringBuffer();
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
conn.connect();
InputStream is=conn.getInputStream();
in = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
logger.warn("---doPost {}?{}"+ url+ param);
return result.toString();
}
public static String doJsonPost(String jsonInfo, String URL) {
long start = System.currentTimeMillis();
logger.warn("---doJsonPost:"+URL);
byte[] xmlData = jsonInfo.getBytes();
BufferedReader in = null;
DataOutputStream printout = null;
StringBuffer result = new StringBuffer("");
try {
URL url = new URL(URL);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("Content-Type", "text/xml");
urlCon.setRequestProperty("Content-length",
String.valueOf(xmlData.length));
printout = new DataOutputStream(urlCon.getOutputStream());
printout.write(xmlData);
printout.flush();
in = new BufferedReader(new InputStreamReader(
urlCon.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (printout != null) {
printout.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
logger.warn("---result:"+result.toString());
logger.warn("---doJsonPost costs:"+(System.currentTimeMillis()-start));
return result.toString();
}
public static JSONObject httpRequest(String requestUrl,
String requestMethod, String outputStr) {
long start = System.currentTimeMillis();
logger.warn("---httpRequest:"+requestUrl);
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
System.out.println(buffer.toString());
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
logger.warn("---httpRequest costs:"+(System.currentTimeMillis()-start));
return jsonObject;
}
public static String httpsRequest(String requestUrl,
String requestMethod, String outputStr) {
long start = System.currentTimeMillis();
logger.warn("---httpRequest:"+requestUrl);
StringBuffer buffer = new StringBuffer();
try {
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("Charset", "UTF-8");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
String responseMessage = httpUrlConn.getResponseMessage();
int responseCode = httpUrlConn.getResponseCode();
System.out.println("responseMessage:"+responseMessage);
System.out.println("responseCode:"+responseCode);
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
String result = buffer.toString();
return result;
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
logger.warn("---httpRequest costs:"+(System.currentTimeMillis()-start));
return "";
}
public static String postMap(String url, Map<String, String> param) {
StringBuffer buffer = new StringBuffer();
for (Entry<String, String> entry : param.entrySet()) {
buffer.append("&").append(entry.getKey())
.append("=").append(entry.getValue());
}
return sendPost(url, buffer.toString());
}
}