通過URLHTTPConnect訪問HTTP和HTTPS服務


通過以下類

//URLHTTPCONNECT連接類

public static String doConnect(String url, String method, Map<String, Object> paramMap) {
HttpURLConnection httpURLConnection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
StringBuffer stringBuffer = new StringBuffer();
String param = JSON.toJSONString(paramMap);

try {
URL addUrl = new URL(url);
httpURLConnection = (HttpURLConnection) addUrl.openConnection();
httpURLConnection.setConnectTimeout(READTIMEOUT);
httpURLConnection.setRequestProperty("Content-type", "application/json");
httpURLConnection.setRequestProperty("charset", "UTF-8");
httpURLConnection.setRequestProperty("accept", "*/*");
// httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod(method);
String timestamp = Long.toString(System.currentTimeMillis());
httpURLConnection.setRequestProperty("timestamp", timestamp);
httpURLConnection.setRequestProperty("authorityToken", TOKEN);
String hash = md532(TOKEN + timestamp + SALT);
httpURLConnection.setRequestProperty("hash", hash);
boolean addHttps = addUrl.toString().startsWith("https");
if (addHttps) {
SSL addSSL = new SSL();
addSSL.trustAllHosts((HttpsURLConnection) httpURLConnection);
((HttpsURLConnection) httpURLConnection).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
}

os = httpURLConnection.getOutputStream();
os.write(param.getBytes());

is = httpURLConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String line;
stringBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
stringBuffer.append(line);
}
// if (httpURLConnection.getResponseCode() == 200) {
// is = httpURLConnection.getInputStream();
// br = new BufferedReader(new InputStreamReader(is));
// String line;
// stringBuffer = new StringBuffer();
// while ((line = br.readLine()) != null) {
// stringBuffer.append(line);
// }
// }
} catch (MalformedURLException e){
System.out.println(e.getMessage());
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(stringBuffer.toString());
return stringBuffer == null ? "" : stringBuffer.toString();
}

 

 

 

 

給connect連接增加SSL證書 用以訪問HTTPS加密連接。

兩種方式:

1.導出瀏覽器的訪問證書。

 

//HTTP的POST方法,用於統一社會信用代碼的申請操作
public static String doPost(Map<String, Object> paramMap) {
String timestamp = Long.toString(System.currentTimeMillis());
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
String result = null;
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(URL);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTTIMEOUT)
.setConnectionRequestTimeout(REQUESTTIMEOUT).setSocketTimeout(SOCKETTIMEOUT).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("authorityToken", TOKEN);
httpPost.setHeader("timestamp", timestamp);
String hash = md532(TOKEN + timestamp + SALT);
httpPost.setHeader("hash", hash);
if (null != paramMap && paramMap.size() > 0) {
httpPost.setEntity(new StringEntity(JSON.toJSONString(paramMap), ENCODING));
try {
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return result;
}

 

 

 

導入證書到JDK:
jdk路徑/bin/keytool -import -v -trustcacerts -alias zjfmpt -file zjfmpt.cer -storepass changeit -keystore ..\jre\lib\security\cacerts

2.使用SSL類進行規避校驗。

 

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SSL {

private static final 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) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};

/**
* 設置不驗證主機
*/
public static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};

/**
* 信任所有
*
* @param connection
* @return
*/
public static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
e.printStackTrace();
}
return oldFactory;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM