4 changed files with 126 additions and 130 deletions
@ -0,0 +1,78 @@ |
|||
package com.win.bank.utils; |
|||
|
|||
import java.io.*; |
|||
import java.net.HttpURLConnection; |
|||
import java.net.URL; |
|||
import java.security.GeneralSecurityException; |
|||
import java.security.KeyStore; |
|||
|
|||
import javax.net.ssl.*; |
|||
|
|||
public class HttpUtil { |
|||
private static final int CONNECT_TIMEOUT = 15000; |
|||
private static final int READ_TIMEOUT = 60000; |
|||
private static final int STATUS_OK = 200; |
|||
|
|||
public static String httpPost(String httpUrl, byte[] data, String charsetName) throws IOException, GeneralSecurityException { |
|||
HttpURLConnection connection = null; |
|||
String result; |
|||
try { |
|||
URL url = new URL(httpUrl); |
|||
SSLContext sslcontext; |
|||
sslcontext = SSLContext.getInstance("SSL"); |
|||
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
|||
tmf.init((KeyStore)null); |
|||
X509TrustManager defaultTm = null; |
|||
for (TrustManager tm : tmf.getTrustManagers()) { |
|||
if (tm instanceof X509TrustManager) { |
|||
defaultTm = (X509TrustManager)tm; |
|||
break; |
|||
} |
|||
} |
|||
sslcontext.init(null, new TrustManager[] {defaultTm}, new java.security.SecureRandom()); |
|||
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory()); |
|||
|
|||
connection = (HttpURLConnection)url.openConnection(); |
|||
connection.setRequestMethod("POST"); |
|||
connection.setConnectTimeout(CONNECT_TIMEOUT); |
|||
connection.setReadTimeout(READ_TIMEOUT); |
|||
connection.setInstanceFollowRedirects(true); |
|||
connection.setDoOutput(true); |
|||
connection.setDoInput(true); |
|||
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); |
|||
|
|||
try (OutputStream os = connection.getOutputStream()) { |
|||
os.write(data); |
|||
if (connection.getResponseCode() != STATUS_OK) { |
|||
InputStream is = connection.getErrorStream(); |
|||
BufferedReader br = new BufferedReader(new InputStreamReader(is, charsetName)); |
|||
StringBuilder sbf = new StringBuilder(); |
|||
String temp; |
|||
while ((temp = br.readLine()) != null) { |
|||
sbf.append(temp); |
|||
sbf.append("\r\n"); |
|||
} |
|||
result = sbf.toString(); |
|||
br.close(); |
|||
is.close(); |
|||
} else { |
|||
InputStream is = connection.getInputStream(); |
|||
BufferedReader br = new BufferedReader(new InputStreamReader(is, charsetName)); |
|||
StringBuilder sbf = new StringBuilder(); |
|||
String temp; |
|||
while ((temp = br.readLine()) != null) { |
|||
sbf.append(temp); |
|||
} |
|||
result = sbf.toString(); |
|||
br.close(); |
|||
is.close(); |
|||
} |
|||
} |
|||
} finally { |
|||
if (connection != null) { |
|||
connection.disconnect(); |
|||
} |
|||
} |
|||
return result; |
|||
} |
|||
} |
Loading…
Reference in new issue