通过httpClient通过post向接口发送xml数据,并处理返回的xml报文
1. springboot读取xml文件
public class loadXML{
public static Document loadConfig() {
Document doc = null;
SAXReader reader = new SAXReader();
try {
// 第一种方式
ClassPathResource classPathResource1 = new ClassPathResource("sendEmail.xml");
InputStream inputStream1 =classPathResource1.getInputStream();
// 第二种方式
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("sendEmail.xml");
// 第三种方式
InputStream resourceAsStream1 = this.getClass().getResourceAsStream("sendEmail.xml");
// 第四种方式 开发可以,生产失败,springboot内置tomcat,打包后是一个jar包,无法直接读取jar包中的文件,读取只能通过类加载器读取。
File file = ResourceUtils.getFile("classpath:sendEmail.xml");
ClassPathResource classPathResource = new ClassPathResource("sendEmail.xml");
InputStream inputStream = classPathResource.getInputStream();
doc = reader.read(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
}
2. 对xml文件进行修改
//需要的maven依赖 https://mvnrepository.com/
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
// 在loadXML文件中的方法 public static String getEmailByNoFile() { Document document = loadXML.loadConfig(); // 获取根节点 Element root = document.getRootElement(); //获取到所有的节点 List<Element> list = root.elements(); //任务描述 root.element("html").element("body).setText("body里面的内容") root.addElement("shu").setText("《老人与海》") //获取xml文件的String形式 String string XML = document.asXML(); }
3. HttpClientUtils
// maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency>
import java.io.IOException; import java.net.URI; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; //import org.apache.commons.collections.MapUtils; import org.apache.http.Consts; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.utils.URIBuilder; 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.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.ContentType; 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.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; /** * * @ClassName: HttpsUtils * @Description: TODO(https post忽略证书请求) */ public class HttpClientUtils { private static final String HTTP = "http"; private static final String HTTPS = "https"; private static SSLConnectionSocketFactory sslsf = null; private static PoolingHttpClientConnectionManager cm = null; private static SSLContextBuilder builder = null; static { try { builder = new SSLContextBuilder(); // 全部信任 不做身份鉴定 builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build(); cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(200);// max connection } catch (Exception e) { e.printStackTrace(); } } // public static String post(String url, Map<String, String> header, Map<String, String> param, StringEntity entity) // throws Exception { // String result = ""; // CloseableHttpClient httpClient = null; // try { // httpClient = getHttpClient(); // //HttpGet httpPost = new HttpGet(url);//get请求 // HttpPost httpPost = new HttpPost(url);//Post请求 // // 设置头信息 // if (MapUtils.isNotEmpty(header)) { // for (Map.Entry<String, String> entry : header.entrySet()) { // httpPost.addHeader(entry.getKey(), entry.getValue()); // } // } // // 设置请求参数 // if (MapUtils.isNotEmpty(param)) { // List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // for (Map.Entry<String, String> entry : param.entrySet()) { // // 给参数赋值 // formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); // } // UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); // httpPost.setEntity(urlEncodedFormEntity); // } // // 设置实体 优先级高 // if (entity != null) { // httpPost.addHeader("Content-Type", "text/xml"); // httpPost.setEntity(entity); // } // HttpResponse httpResponse = httpClient.execute(httpPost); // int statusCode = httpResponse.getStatusLine().getStatusCode(); // System.out.println("状态码:" + statusCode); // if (statusCode == HttpStatus.SC_OK) { // HttpEntity resEntity = httpResponse.getEntity(); // result = EntityUtils.toString(resEntity); // } else { // readHttpResponse(httpResponse); // } // } catch (Exception e) { // throw e; // } finally { // if (httpClient != null) { // httpClient.close(); // } // } // return result; // } public static String postXML(String url,String xml){ CloseableHttpClient client = null; CloseableHttpResponse resp = null; try{ HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8"); client = HttpClients.createDefault(); StringEntity entityParams = new StringEntity(xml,"utf-8"); httpPost.setEntity(entityParams); client = HttpClients.createDefault(); resp = client.execute(httpPost); String resultMsg = EntityUtils.toString(resp.getEntity(),"utf-8"); return resultMsg; }catch (Exception e){ e.printStackTrace(); }finally { try { if(client!=null){ client.close(); } if(resp != null){ resp.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } public static CloseableHttpClient getHttpClient() throws Exception { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm) .setConnectionManagerShared(true).build(); return httpClient; } public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException { StringBuilder builder = new StringBuilder(); // 获取响应消息实体 HttpEntity entity = httpResponse.getEntity(); // 响应状态 builder.append("status:" + httpResponse.getStatusLine()); builder.append("headers:"); HeaderIterator iterator = httpResponse.headerIterator(); while (iterator.hasNext()) { builder.append("\t" + iterator.next()); } // 判断响应实体是否为空 if (entity != null) { String responseString = EntityUtils.toString(entity); builder.append("response length:" + responseString.length()); builder.append("response content:" + responseString.replace("\r\n", "")); } return builder.toString(); } /** * get发送数据 * @param url * @param param * @return */ public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } /** * get发送数据 * @param url * @return */ public static String doGet(String url) { return doGet(url, null); } /** * post发送数据 * @param url * @param param * @return */ public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } /** * post发送数据 * @param url * @return */ public static String doPost(String url) { return doPost(url, null); } /** * post发送json形式的数据 * @param url * @param json * @return */ public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } }
4. 用httpUtils发送数据
String result = HttpClientUtils.postXML("http://127.0.0.1:8081/platformEmail/parseXML", document.asXML()); // 把返回结果进行解析 @RestController @RequestMapping("/platformEmail") public class RequestController { @RequestMapping(value = "/parseXML",method = RequestMethod.POST) public void parse(@RequestBody String parseXML) throws Exception { Document document = DocumentHelper.parseText(parseXML); Element rootElement = document.getRootElement(); String reqcode = rootElement.element("reqcode").getText(); String user = rootElement.element("user").getText(); System.out.println(reqcode); System.out.println(user); } }