httpClient发送https 请求
做项目要用到httpClient发送https到服务器,要求URL中带参数,并且发送xml格式的报文,第一次做,在这里记录一下,以便以后查询的帮助别人:本文在证书配置正确的前提下执行
客户端代码;
public static void httpsRequest() throws Exception { System.out.println("this is https"); KeyStore trustStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(STORE); System.out.println(instream); try { trustStore.load(instream, PASSWD.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("sign", sign("timestamp"+timestamp+"v"+V))); nvps.add(new BasicNameValuePair("timestamp", "timestamp")); nvps.add(new BasicNameValuePair("v", "1.0")); HttpPost httpPost = new HttpPost(URL+"?"+ URLEncodedUtils.format(nvps, "UTF-8")); StringEntity sendbody = new StringEntity(xmlData+getParams(),"UTF-8"); httpPost.setEntity(sendbody); httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); System.out.println("executing request " + httpPost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
客户端,运行结果
服务器代码,证书配置在tomcat的server.xml中;
public String infoQuery(){ System.out.println("+++++++++++++++++++++++++++++++"); try { HttpServletRequest request = ServletActionContext.getRequest(); String version = request.getParameter("v"); String timestamp = request.getParameter("timestamp"); String sign = request.getParameter("sign"); System.out.println(version); System.out.println(timestamp); System.out.println(sign); byte[] buffer = new byte[1024]; int length = request.getInputStream().read(buffer); String encode = request.getCharacterEncoding(); System.out.println(length + " <<<>>> " + encode ); byte[] data = new byte[length]; System.arraycopy(buffer, 0, data, 0, length); String content = new String(data, encode); System.out.println(content); } catch (IOException e) { logger.error("",e); } System.out.println("ssssssddddddsssssssss"); return SUCCESS; }
服务器运行结果
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。