1.場景描述
使用Apache開源組織中的HttpComponents,完成對http服務器的訪問功能,消息體xml報文。
2.HttpComponents項目的介紹
HttpComponents項目就是專門設計來簡化HTTP客戶端與服務器進行各種通訊編程。通過它可以讓原來很頭疼的事情現在輕松的解決,例如你不再管是HTTP或者HTTPS的通訊方式,告訴它你想使用HTTPS方式,剩下的事情交給 httpclient替你完成。
3.maven依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.1</version> </dependency>
4.代碼編寫
工具類
import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; 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.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * apache httpclient 工具類 * 支持對 http https 接口調用 * <P> * 1.GET 請求 * 2.POST 請求 * </P> */ public class HttpDelegate { private int timeOut = 10000;//指定超時時間 private CloseableHttpClient httpClient; private RequestConfig requestConfig;//設置請求參數 /** * 對象被創建時執行 */ public HttpDelegate(Boolean isHttps){ httpClient = this.getHttpClient(isHttps); this.initRequestConfig();//初始化請求配置 } /** * 發送post請求 * @param url 請求地址 * @param contentType 請求類型 * @param encoding 編碼格式 * @param param 請求參數 * @return */ public String executePost(String url,String contentType,String encoding,String param) { HttpPost httpPost = new HttpPost(url); try { httpPost.setConfig(requestConfig); this.initMethodParam(httpPost, contentType, encoding); if(param!=null) { httpPost.setEntity(new StringEntity(param, encoding));//設置請求體 } return this.execute(httpPost,httpClient); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { httpPost.releaseConnection(); } } /** * 發送get請求 * @param url 請求地址 * @param contentType 請求類型 * @param encoding 編碼格式 * @return */ public String executeGet(String url,String contentType,String encoding){ HttpGet httpGet = new HttpGet(url); try{ httpGet.setConfig(requestConfig); this.initMethodParam(httpGet, contentType, encoding); return this.execute(httpGet,httpClient); }catch (Exception e){ throw new RuntimeException(e.getMessage(),e); }finally{ httpGet.releaseConnection(); } } /** * 通用方法,用來發送post或get請求 * @param method 請求類型 * @param httpClient * @return * @throws RuntimeException * @throws IOException */ private String execute(HttpUriRequest method,CloseableHttpClient httpClient) throws RuntimeException,IOException{ CloseableHttpResponse response = null; try{ response = httpClient.execute(method); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, method.getFirstHeader(HttpHeaders.CONTENT_ENCODING).getValue()); }catch (Exception e){ throw new RuntimeException(e.getMessage(), e); }finally{ if(response != null){ response.close(); } } } private void initMethodParam(HttpUriRequest method, String contentType, String encoding){ if (contentType != null){ method.setHeader(HttpHeaders.CONTENT_TYPE, contentType); } method.setHeader(HttpHeaders.CONTENT_ENCODING, encoding); method.setHeader(HttpHeaders.TIMEOUT, "60000"); } /** * 設置初始值 */ private void initRequestConfig() { requestConfig=RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build(); } /** * 獲取主體類: * isHttps 區分https 和 https * @param isHttps * @return */ private CloseableHttpClient getHttpClient(boolean isHttps) { CloseableHttpClient chc = null; try{ if (isHttps){ TrustManager[] trustManagers = new TrustManager[1]; trustManagers[0] = new X509TrustManager(){ public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{} public X509Certificate[] getAcceptedIssuers(){ return null; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[0], trustManagers, new SecureRandom()); SSLContext.setDefault(sslContext); sslContext.init(null, trustManagers, null); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); chc = HttpClients.custom().setSSLSocketFactory(sslsf).build(); }else{ chc=HttpClients.custom().build(); } }catch (Exception e){ throw new RuntimeException(e.getMessage(), e); } return chc; } /** * 關閉鏈接 */ public void destroy(){ System.out.println("方法被執行"); try{ httpClient.close(); }catch (IOException e){ throw new RuntimeException(e.getMessage(),e); } } }
服務端接口
@RequestMapping(value="/txp/test.action",method= RequestMethod.POST) public void testHttpPost(HttpServletRequest request, HttpServletResponse response) throws Exception{ //解析請求報文 request.setCharacterEncoding("UTF-8"); //返回頁面防止出現中文亂碼 BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));//post方式傳遞讀取字符流 String jsonStr = null; StringBuilder sb = new StringBuilder(); try { while ((jsonStr = reader.readLine()) != null) { sb.append(jsonStr); } } catch (IOException e) { e.printStackTrace(); } reader.close();// 關閉輸入流 System.out.println("請求報文:"+sb.toString()); String result = "true"; response.getWriter().print(result); }
測試方法
@Test public void test(){ //組裝回調參數 StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<root>"); sb.append("<param1>").append("hello word").append("</param1>"); sb.append("<param2>").append("!").append("</param2>"); sb.append("</root>"); //開始進行回調 log.info("回調信息,{}",sb.toString()); String responseBody = hd.executePost("http://localhost:7082/ecurrency-cardtransfer/txp/test.action", "text/xml", "GBK", sb.toString()); System.out.println("返回信息:"+responseBody); }
