欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > java开发常用工具类

java开发常用工具类

2024/11/29 18:13:57 来源:https://blog.csdn.net/weixin_45146962/article/details/143379594  浏览:    关键词:java开发常用工具类

文章目录

  • xml与json互转
  • java调用wsdl接口

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-typeconnection.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-typeconnection.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=GetPlanMaterilDetailString 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=UpdateSupplierInventoryDataString 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;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com