1、java.lang.ClassCastException: org.apache.xerces.dom.DocumentImpl cannot be cast to java.lang.String
cfx服务端代码参考https://blog.csdn.net/zwahut/article/details/100923439
xfire客户端代码如下:
import org.codehaus.xfire.client.Client;
import java.net.URL;
import java.net.URLDecoder;
public class Test {
private static String WSDL = "";
static{
WSDL = "http://localhost:8080/userWebService?wsdl";
}
public static void main(String[] args){
getAllUsers();
}
public static void getAllUsers() {
String result = "";
try {
Client client = new Client(new URL(WSDL));
Object[] results = client.invoke("getUserByName", new Object[]{"李四"});
result = URLDecoder.decode((String)results[0],"utf-8");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行报错,错误信息:
java.lang.ClassCastException: org.apache.xerces.dom.DocumentImpl cannot be cast to java.lang.String
at com.chinaoly.Test.getAllUsers(Test.java:35)
at com.chinaoly.Test.main(Test.java:22)
错误原因是返回结果需要转换成Document对象,修改代码如下:
import org.codehaus.xfire.client.Client;
import org.w3c.dom.Document;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLDecoder;
public class Test {
private static String WSDL = "";
static{
WSDL = "http://localhost:8080/userWebService?wsdl";
}
public static void main(String[] args){
getAllUsers();
}
public static void getAllUsers() {
String result = "";
try {
Client client = new Client(new URL(WSDL));
Object[] results = client.invoke("getUserByName", new Object[]{"李四"});
Document d = (Document)results[0];
System.out.println(toFormatedXML(d));
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String toFormatedXML(Document doc) throws Exception {
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transFormer = transFactory.newTransformer();
transFormer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource domSource = new DOMSource(doc);
StringWriter sw = new StringWriter();
StreamResult xmlResult = new StreamResult(sw);
transFormer.transform(domSource, xmlResult);
return sw.toString();
}
}
运行结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><return><id>001</id><name>李四</name></return>