Java 通过HttpClient 带证书方式请求Https协议网站 (Post方式带xml文档,Get以及Delete方式)
2017-06-30 10:27
1041 查看
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、完整代码,其中注释基本完整
package com.hp.http; 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="https请求路径"; String docXmlText =getXml("Xml文档路径"); String cerPath="truststore证书路径"; String passWord="密码"; String deleteId=null; /* * Get方式 */ HttpGet httpGet=getHttpGet(url);//创建HttpGet对象 String bodyGet = send(url, "utf-8",httpGet,cerPath,passWord); System.out.println(bodyGet); //打印post response /* * Post方式带参数 */ HttpPost httpPost=getHttpPostXml(url, docXmlText);//创建HttpPost对象 String bodyPost = send(url, "utf-8",httpPost,args[0],args[1]); //执行HttpPost请求 System.out.println(bodyPost); //打印post response /* * Delete方式 */ HttpDelete httpDelete=getHttpDelete(url+"/这里填DeleteId"); //创建HTTPDelete 对象 String bodyDelete = send(args[2], "utf-8",httpDelete,args[0],args[1]); //执行HttpDelete请求 System.out.println(bodyDelete); //打印delete response } /** * * @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 d 4000 ocXmlText; } /** * 证书验证 * @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; } }
相关文章推荐
- Java 通过httpClient Post方式提交xml,并从服务端返回数据
- 【HttpClient】JAVA利用HttpClient进行POST和GET请求(HTTPS)
- HTTP协议请求方式: 中GET、POST和HEAD的介绍以及错误提示码
- java发送post和get请求(1)---HttpClient 方式
- HttpClient详解,Java发送Http的post、get方式请求 --待整理
- http协议中的几种请求的方式(Get、Post、Put、Head、Delete、Options、Trace和Connect)
- 同步和异步Httpclient通过get和post方式发送请求
- HTTP协议中POST、GET、HEAD、PUT等请求方法以及一些常见错误
- java http get post请求 https请求实现
- 【Java】HttpURLConnection,HttpClient 的 Get,Post 请求
- PB9.0 通过http协议以POST方式将XML发送到协议服务器[转]
- java httpclient发送post get 请求
- java apache commons HttpClient发送get和post请求的学习整理
- C#通过WebClient/HttpWebRequest实现http的post/get方法与java对接
- python实现的json数据以HTTP GET,POST,PUT,DELETE方式页面请求
- java实现:http协议get和post方法的url参数请求响应及交互
- 简单记下httpclientjava实现get,post请求
- 通过http/https的POST方式,发送和接受XML文件内容
- HttpClient 的GET(带参数)、POST请求方式,工具类方法
- XMLHttpRequest发送POST、GET请求以及接收返回值