import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* 发送https请求
* @param jsonParams
* @return
* @throws KeyStoreException
* @throws IOException
* @throws FileNotFoundException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
*/
@SuppressWarnings("deprecation")
public static String HttpsProcess(String httpsUrl , String keyStorePath , String keyPass , String jsonParams) throws KeyStoreException, NoSuchAlg orithmException, CertificateException, FileNotFoundException, IOException, KeyManagementException, UnrecoverableKeyException {
logger.info("param httpsUrl:"+httpsUrl); //url 记得用https://ip:8443/***
logger.info("param keyStorePath:"+keyStorePath); //keyStorePath 将server端(接受https请求的web server)的ssh key 文件存放到本地(该类文件存在的地方)该keyStorePath 为存放路径
logger.info("param keyPass:"+"**********"); //server 端生成 ssh key 的password
logger.info("param jsonParams:"+jsonParams); // 要发送的数据
if(StringUtils.isNullOrEmpty(httpsUrl) ||
StringUtils.isNullOrEmpty(keyStorePath) ||
StringUtils.isNullOrEmpty(keyPass) ||
StringUtils.isNullOrEmpty(jsonParams))
{
logger.info("同步数据参数为NULL");
logger.error("同步数据参数为NULL");
return Constant.PARAMETER_ERROR_CODE;
}
org.apache.http.client.HttpClient hc = new org.apache.http.impl.client.DefaultHttpClient();
java.security.KeyStore trustStore = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
//"123456"为制作证书时的密码
trustStore.load(new FileInputStream(new File(keyStorePath)), keyPass.toCharArray());
org.apache.http.conn.ssl.SSLSocketFactory socketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(trustStore);
//不校验域名
socketFactory.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//这个8446是和被访问端约定的端口,一般为443
org.apache.http.conn.scheme.Scheme sch = new org.apache.http.conn.scheme.Scheme("https", socketFactory, 8443);
hc.getConnectionManager().getSchemeRegistry().register(sch);
org.apache.http.client.methods.HttpPost httpost = new org.apache.http.client.methods.HttpPost(httpsUrl);
httpost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpost.setEntity(new StringEntity(jsonParams, HTTP.UTF_8 ));
org.apache.http.HttpResponse hres = hc.execute(httpost);
org.apache.http.HttpEntity entity = hres.getEntity();
String result = EntityUtils.toString(entity);
result = result != null ? result.replace("\"", "") : result;
return result;
}
java send https request small instance
最新推荐文章于 2023-05-17 09:50:36 发布