通过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("l");
InputStream inputStream1 =InputStream();
/
/ 第⼆种⽅式
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("l");
// 第三种⽅式
InputStream resourceAsStream1 = Class().getResourceAsStream("l");
// 第四种⽅式开发可以,⽣产失败,springboot内置tomcat,打包后是⼀个jar包,⽆法直接读取jar包中的⽂件,读取只能通过类加载器读取。
File file = File("l");
ClassPathResource classPathResource = new ClassPathResource("l");
InputStream inputStream = InputStream();
doc = ad(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
}
2. 对xml⽂件进⾏修改
//需要的maven依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
// 在loadXML⽂件中的⽅法
public static String getEmailByNoFile() {
Document document = loadXML.loadConfig();
// 获取根节点
Element root = RootElement();
//获取到所有的节点
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.URI;
import CertificateException;
import X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import llections.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.ity.UrlEncodedFormEntity;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.fig.Registry;
import org.fig.RegistryBuilder;
import org.socket.ConnectionSocketFactory;
import org.socket.PlainConnectionSocketFactory;
import org.ssl.NoopHostnameVerifier;
import org.ssl.SSLConnectionSocketFactory;
import org.ssl.TrustStrategy;
import org.ity.ContentType;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.PoolingHttpClientConnectionManager;
import org.ssage.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 : Set()) {
// httpPost.Key(), Value());
// }
// }
//// 设置请求参数
// if (MapUtils.isNotEmpty(param)) {
// List<NameValuePair> formparams = new ArrayList<NameValuePair>();
// for (Map.Entry<String, String> entry : Set()) {
//// 给参数赋值
// formparams.add(new Key(), Value()));
// }
// 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 = ute(httpPost);
// int statusCode = StatusLine().getStatusCode();
// System.out.println("状态码:" + statusCode);
// if (statusCode == HttpStatus.SC_OK) {
// HttpEntity resEntity = Entity();
// result = String(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 = ateDefault();
StringEntity entityParams = new StringEntity(xml,"utf-8");
httpPost.setEntity(entityParams);
client = ateDefault();
resp = ute(httpPost);
String resultMsg = Entity(),"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 = Entity();
// 响应状态
builder.append("status:" + StatusLine());
builder.append("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
builder.append("\t" + ());
}
// 判断响应实体是否为空
if (entity != null) {
String responseString = String(entity);
builder.append("response length:" + responseString.length());
builder.append("response content:" + place("\r\n", ""));
}
String();
}
/**
* get发送数据
* @param url
* @param param
* @return
*/
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = ateDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
/
/ 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, (key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
dom4j读取xml// 执⾏请求
response = ute(httpGet);
// 判断返回状态是否为200
if (StatusLine().getStatusCode() == 200) {
resultString = Entity(), "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 = ateDefault();
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, (key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); httpPost.setEntity(entity);
}
// 执⾏http请求
response = ute(httpPost);
resultString = Entity(), "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 = ateDefault();
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 = ute(httpPost);
resultString = Entity(), "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("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 = RootElement();
String reqcode = rootElement.element("reqcode").getText();
String user = rootElement.element("user").getText();
System.out.println(reqcode);
System.out.println(user);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论