通过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 ..jrelibsecuritycacerts

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;
}
}

原文地址:https://www.cnblogs.com/UUUz/p/12308517.html