首页 » Java » Java 通过HttpClient 带证书方式请求Https协议网站 (Post带xml文档

Java 通过HttpClient 带证书方式请求Https协议网站 (Post带xml文档

2017-06-29 18:20:41阅读(5254)

1、所需依赖

<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>HttpClient</artifactId>
	    <version>4.5.2</version>
	</dependency>  
	<dependency>
	    <groupId>dom4j</groupId>
	    <artifactId>dom4j</artifactId>
	    <version>1.6.1</version>
	</dependency>

2、完整代码,其中注释基本完整,

其中Java证书生成请参考下一篇博客

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class HttpClient {
	/**
	 * 
	 * @param args 0 证书  1 密码  2 delete链接 3
	 * @throws DocumentException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void main(String[] args) throws DocumentException, ClientProtocolException, IOException {
		/*	String url="*******************";
			String docXmlText =getXml("C:/signingservice/signingData.xml");	
			HttpPost httpPost=getHttpPostXml(url, docXmlText);//创建HttpPost对象
			String bodyPost = send(url, "utf-8",httpPost,args[0],args[1]);*/
		
			HttpDelete httpDelete=getHttpDelete(args[2]); //创建HTTPDelete 对象
			String bodyDelete = send(args[2], "utf-8",httpDelete,args[0],args[1]);  //执行HttpDelete请求
		   	System.out.println(bodyDelete);	   //打印delete response
		    	//String docXmlText =getXml("C:/signingservice/signingData.xml");
			//String cerPath="C:/cert/hptruststore";
			//String passWord="1qaz2wsx";	
		 	/*String deleteId = null;
			//post带xml请求Https
			
			String docXmlText =getXml("C:/signingservice/signingData.xml");//xml文档
			
			
			String cerPath="C:/cert/hptruststore";//证书路径


			
			String passWord="*****";//证书密码
			String url="*******";//https访问地址



			HttpPost httpPost=getHttpPostXml(url, docXmlText);//创建HttpPost对象
			
			String bodyPost = send(url, "utf-8",httpPost,cerPath,password);//执行HttpPost请求
System.out.println(bodyPost);Pattern p=Pattern.compile("\\d+"); //正则匹配获取Post产生delete的IDMatcher m=p.matcher(bodyPost); //打印post responseif(m.find())deleteId=m.group(); //匹配到ID */}/** * * @param Xml文件路径 * @return Xml 文件字符串 * @throws DocumentException */public static String getXml(String url) throws DocumentException{SAXReader reader = new SAXReader(); // 读取一个文件,把这个文件转成Document对象 Document document = reader.read(new File(url)); // 获取根元素 Element root = document.getRootElement(); // 把文档转成字符串 String docXmlText = document.asXML(); return docXmlText;}/** * 证书验证 * @param keyStorePath 生成keyStore的路径 * @param keyStorepass 对应keyStore的密码 * @return */public static SSLContext custom(String keyStorePath, String keyStorepass){ SSLContext sc = null; FileInputStream instream = null; KeyStore trustStore = null; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); instream = new FileInputStream(new File(keyStorePath)); trustStore.load(instream, keyStorepass.toCharArray()); // 相信自己的CA和所有自签证书 sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); } catch (Exception e) { e.printStackTrace(); } finally { try { instream.close(); } catch (IOException e) { } } return sc;}/** * * @param url进行Get请求的地址 * @return 返回HttpGet */public static HttpGet getHttpGet(String url){HttpGet httpGet = new HttpGet(url);return httpGet;} /** * * @param url 进行Post请求的地址 * @param Xml 传输的Xml文件对应的字符串 * @return 返回HttpPost */public static HttpPost getHttpPostXml(String url,String Xml){ HttpPost httpPost = new HttpPost(url); HttpEntity requestEntity = new StringEntity(Xml, "UTF-8"); //设置请求体 httpPost.setEntity(requestEntity); httpPost.addHeader("Content-Type", "application/xml"); //设置请求头 return httpPost;} /** * * @param url 进行Delete请求的地址 * @param id Delete删除的Id * @return 返回HttpDelete */public static HttpDelete getHttpDeleteId(String url,String id){ HttpDelete httpDelete=new HttpDelete(url+"/"+id); return httpDelete;}public static HttpDelete getHttpDelete(String url){ HttpDelete httpDelete=new HttpDelete(url); return httpDelete;}public static String send(String url, String encoding,HttpUriRequest method,String cerPath,String cerPassword) throws ClientProtocolException, IOException { String body = ""; SSLContext sslcontext = custom(cerPath, cerPassword); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext)).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build(); CloseableHttpResponse response = client.execute(method); //执行相应方法请求 System.err.println(method.toString().split("http")[0]+response.getStatusLine().getStatusCode()); //获取响应状态码 HttpEntity entity = response.getEntity(); //获取响应实体 if (entity != null) { body = EntityUtils.toString(entity, encoding); //实体转字符串 } // EntityUtils.consume(entity); response.close(); return body; }}



最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹