调用webservice接口,xml传输

  • Post author:
  • Post category:其他


public class XmlConvertUtil {
    /**
     * xml转换成JavaBean
     *
     * @param xml xml格式字符串
     * @param t 待转化的对象
     * @return 转化后的对象
     * @throws Exception JAXBException
     */
    @SuppressWarnings({ "unchecked" })
    public static <T> T convertToJavaBean(String xml, Class<T> t) throws Exception {
        T obj = null;
        JAXBContext context = JAXBContext.newInstance(t);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        obj = (T) unmarshaller.unmarshal(new StringReader(xml));
        return obj;
    }

    /**
     * JavaBean转换成xml
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding==null?"utf-8":encoding);

            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
public class WebServiceUtil {

    public static String callWeb(String... params) throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        String methodName = "";
        String namespace = "";
        QName qName = new QName(namespace, methodName);
        Client client = dcf.createClient("");
        Object[] objects;
        // invoke("方法名",参数1,参数2,参数3....);
        objects = client.invoke(qName, params);
        return objects[0].toString();
    }
}

实体类:

@Data
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "Response")
public class XXXResponse {

    @XmlElement(name = "Result")
    @ApiModelProperty(value = "结果")
    private String result;

    @XmlElementWrapper(name = "Results")
    @XmlElement(name = "Result")
    @ApiModelProperty(value = "数据集合")
    private List<Result> results;
}



版权声明:本文为m0_63140848原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。