java开发常用工具类

文章目录

xml与json互转

复制代码
package com.epichust.unimax.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class HxXmlJsonUtil {

	/**
	 * xml转json方法
	 * @param xml
	 * @return
	 */
	public static JSONObject xmlToJson(String xml) {
		return elementToJson((strToDocument(xml)).getRootElement());
	}

	/**
	 * json转xml方法
	 * @param json
	 * @return
	 */
	public static String jsonToXml(String json) {
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			JSONObject jObj = JSON.parseObject(json);
			jsonToXmlStr(jObj, buffer);
			return buffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private static Document strToDocument(String xml) {
		try {
			return DocumentHelper.parseText(xml);
		} catch (DocumentException e) {
			return null;
		}
	}

	private static JSONObject elementToJson(Element node) {
		JSONObject result = new JSONObject();
		List<Attribute> listAttr = node.attributes();
		for (Attribute attr : listAttr) {
			result.put(attr.getName(), attr.getValue());
		}
		List<Element> listElement = node.elements();
		if (!listElement.isEmpty()) {
			for (Element e : listElement) {
				if (e.attributes().isEmpty() && e.elements().isEmpty()) {
					result.put(e.getName(), e.getTextTrim());
				} else {
					if (!result.containsKey(e.getName())) {
						result.put(e.getName(), new JSONArray());
					}
					((JSONArray) result.get(e.getName())).add(elementToJson(e));
				}
			}
		}
		return result;
	}

	private static void jsonToXmlStr(JSONObject jObj, StringBuffer buffer) {
		Set<Map.Entry<String, Object>> se = jObj.entrySet();
		for (Map.Entry<String, Object> en : se) {
			if ("com.alibaba.fastjson.JSONObject".equals(en.getValue().getClass().getName())) {
				buffer.append("<").append(en.getKey()).append(">");
				JSONObject jo = jObj.getJSONObject(en.getKey());
				jsonToXmlStr(jo, buffer);
				buffer.append("</").append(en.getKey()).append(">");
			} else if ("com.alibaba.fastjson.JSONArray".equals(en.getValue().getClass().getName())) {
				JSONArray jarray = jObj.getJSONArray(en.getKey());
				for (int i = 0; i < jarray.size(); i++) {
					buffer.append("<").append(en.getKey()).append(">");
					JSONObject jsonobject = jarray.getJSONObject(i);
					jsonToXmlStr(jsonobject, buffer);
					buffer.append("</").append(en.getKey()).append(">");
				}
			} else if ("java.lang.String".equals(en.getValue().getClass().getName())) {
				buffer.append("<").append(en.getKey()).append(">").append(en.getValue());
				buffer.append("</").append(en.getKey()).append(">");
			}
		}
	}
}

java调用wsdl接口

复制代码
package com.epichust.unimax.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.epichust.mestar.logging.MestarLogger;
import com.epichust.mestar.utils.exception.MestarException;


public class WSDLUtil {
	
    public static void main(String[] args) throws IOException {
    	String queryAddress = "https://lmes.sdlg.cn:6443/WebService/SupplierService/SupplierService.asmx?wsdl";
    	String method = "POST";
    	String soapXML = getPlanMaterilDetailXML("43273_Service","J2Zprw2BCDZRHD24","8509","LGLLINE1","0000043273","2024-03-11","2024-03-12");
    	String queryWsdlData = queryWsdlData(queryAddress,method,soapXML);
    	System.out.println(queryWsdlData);
    }
    
    /**
     * 请求wsdl接口
     * @param queryAddress 请求地址
     * @param method 请求方法:post,get
     * @param soapXML 请求内容
     * @return
     */
	public static String queryWsdlData(String queryAddress,String method,String soapXML){
		MestarLogger.error("queryWsdlData() 请求地址:"+queryAddress+",请求参数:"+soapXML);
		OutputStream os = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			//第一步:创建服务地址  //http://ws.webxml.com.cn/
			URL url = new URL(queryAddress);
			//第二步:打开一个通向服务地址的连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			//第三步:设置参数
			//3.1发送方式设置:POST必须大写
			connection.setRequestMethod(method);
			//3.2设置数据格式:content-type
			connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
			//3.3设置输入输出,因为默认新创建的connection没有读写权限,
			connection.setDoInput(true);
			connection.setDoOutput(true);
			//第四步:组织SOAP数据,发送请求
//			String soapXML = getXML("43273_Service","J2Zprw2BCDZRHD24","8509","LGLLINE1","0000043273","2024-03-10","2024-03-12");
			//将信息以流的方式发送出去
			os = connection.getOutputStream();
			os.write(soapXML.getBytes(StandardCharsets.UTF_8));
			//第五步:接收服务端响应,打印
			int responseCode = connection.getResponseCode();
			if(200 == responseCode){//表示服务端响应成功
				//获取当前连接请求返回的数据流
				is = connection.getInputStream();
				isr = new InputStreamReader(is,"UTF-8");
				br = new BufferedReader(isr);
				StringBuilder sb = new StringBuilder();
				String temp = null;
				while(null != (temp = br.readLine())){
					sb.append(temp);
				}
				MestarLogger.error("queryWsdlData()请求"+queryAddress+"成功,返回数据:"+sb.toString());
				return sb.toString();
			}
			MestarLogger.error("queryWsdlData()请求"+queryAddress+"失败,返回数据:null");
			return null;
		} catch (Exception e) {
			MestarLogger.error("queryWsdlData() 请求"+queryAddress+"失败,失败原因:"+e.getMessage());
			throw new MestarException("请求"+queryAddress+"失败,失败原因:"+e.getMessage());
		}finally {//关闭流
			try {
				if (is != null) {	
					is.close();
				}
				if (isr != null) {
					isr.close();
				}
				if (br != null) {
					br.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (Exception e) {
				MestarLogger.error("queryWsdlData() 关闭流失败")	;
				e.printStackTrace();
			}
		}
	}
	
    //请求WSDL地址获取参数 ;action=\""+content+"\"
	public static String queryWsdlDataForJINDIE(String queryAddress,String method,String soapXML,String content){
		MestarLogger.error("queryWsdlDataForJINDIE() 请求地址:"+queryAddress+",请求参数:"+soapXML);
		OutputStream os = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			//第一步:创建服务地址  //http://ws.webxml.com.cn/
			URL url = new URL(queryAddress);
			//第二步:打开一个通向服务地址的连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			//第三步:设置参数
			//3.1发送方式设置:POST必须大写
			connection.setRequestMethod(method);
			//3.2设置数据格式:content-type
			connection.setRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8");
			//3.3设置输入输出,因为默认新创建的connection没有读写权限,
			connection.setDoInput(true);
			connection.setDoOutput(true);
			//第四步:组织SOAP数据,发送请求
//			String soapXML = getXML("43273_Service","J2Zprw2BCDZRHD24","8509","LGLLINE1","0000043273","2024-03-10","2024-03-12");
			//将信息以流的方式发送出去
			os = connection.getOutputStream();
			os.write(soapXML.getBytes(StandardCharsets.UTF_8));
			//第五步:接收服务端响应,打印
			int responseCode = connection.getResponseCode();
			if(200 == responseCode){//表示服务端响应成功
				//获取当前连接请求返回的数据流
				is = connection.getInputStream();
				isr = new InputStreamReader(is,"UTF-8");
				br = new BufferedReader(isr);
				StringBuilder sb = new StringBuilder();
				String temp = null;
				while(null != (temp = br.readLine())){
					sb.append(temp);
				}
				MestarLogger.error("queryWsdlData()请求"+queryAddress+"成功,返回数据:"+sb.toString());
				return sb.toString();
			}
			MestarLogger.error("queryWsdlData()请求"+queryAddress+"失败,返回数据:null");
			return null;
		} catch (Exception e) {
			MestarLogger.error("queryWsdlData() 请求"+queryAddress+"失败,失败原因:"+e.getMessage());
			throw new MestarException("请求"+queryAddress+"失败,失败原因:"+e.getMessage());
		}finally {//关闭流
			try {
				if (is != null) {	
					is.close();
				}
				if (isr != null) {
					isr.close();
				}
				if (br != null) {
					br.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (Exception e) {
				MestarLogger.error("queryWsdlData() 关闭流失败")	;
				e.printStackTrace();
			}
		}
	}
    
	//GetPlanMaterilDetail方法参数拼接
    public static String getPlanMaterilDetailXML(String account,String pwd,String plant,String prodLine,String parmaCode,String planOnlineTimeStart,String planOnlineTimeEnd){
        //https://lmes.sdlg.cn:6443/WebService/SupplierService/SupplierService.asmx?op=GetPlanMaterilDetail
        String soapXML ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "  <soap:Header>" +
                "    <AuthorizeHeader xmlns=\"http://tempuri.org/\">" +
                "      <Account>"+account+"</Account>" +
                "      <Pwd>"+pwd+"</Pwd>" +
                "    </AuthorizeHeader>" +
                "  </soap:Header>" +
                "  <soap:Body>" +
                "    <GetPlanMaterilDetail xmlns=\"http://tempuri.org/\">" +
                "      <Plant>"+plant+"</Plant>" +
                "      <ProdLine>"+prodLine+"</ProdLine>" +
                "      <ParmaCode>"+parmaCode+"</ParmaCode>" +
                "      <PlanOnlineTime_Start>"+planOnlineTimeStart+"</PlanOnlineTime_Start>" +
                "      <PlanOnlineTime_End>"+planOnlineTimeEnd+"</PlanOnlineTime_End>" +
                "    </GetPlanMaterilDetail>" +
                "  </soap:Body>" +
                "</soap:Envelope>";
        return soapXML;
    }
    
  //GetPlanMaterilDetail方法参数拼接
    public static String updateSupplierInventoryDataXML(String account,String pwd,String data){
        //https://lmes.sdlg.cn/WebService/SupplierService/SupplierService.asmx?op=UpdateSupplierInventoryData
        String soapXML ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "  <soap:Header>" +
                "    <AuthorizeHeader xmlns=\"http://tempuri.org/\">" +
                "      <Account>"+account+"</Account>" +
                "      <Pwd>"+pwd+"</Pwd>" +
                "    </AuthorizeHeader>" +
                "  </soap:Header>" +
                "  <soap:Body>" +
                "<UpdateSupplierInventoryData xmlns=\"http://tempuri.org/\">"
                + "      <InventoryData>"+data+"</InventoryData>"
                + "    </UpdateSupplierInventoryData>"+
                "  </soap:Body>" +
                "</soap:Envelope>";
        return soapXML;
    }
}
相关推荐
EatFan6 小时前
Spring Boot 4.0 升级清单:JDK 基线、Jakarta 命名空间、Observation API 与第三方组件兼容一次讲清
java·spring boot·后端
辰海Coding7 小时前
平台如何接入一台物联网设备?又该如何设计它的通信协议?
java·物联网
代码民工正电荷7 小时前
JAVA重要知识点和集合
java·开发语言
李少兄8 小时前
IDEA Apifox Helper 插件踩坑:2.0.15-243 版本“导出指定接口”参数描述丢失问题解析与修复方案
java·ide·intellij-idea
努力攀登的小k9 小时前
《新手练表:从建表到删表全操作|从零学会表操作》
java·数据库·mysql
Yetian_20009 小时前
Postman测试上传图片文件接口
java·postman
爪哇碎碎念10 小时前
【Java】从一次 cache.get(key) 进去:缓存击穿一瞬间打出 200 次 DB,JDK 17 实测三种解法
java·redis·缓存
csdn_aspnet10 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
源码_空间10 小时前
基于Springboot的在线编程练习判题平台(源码+文档)
java·spring boot·后端
小手cool11 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法