一个webservice客户端纠结了我一个星期的时间,让我天天做噩梦。网上的资料都只讲到怎么在webservice工程中生成xfire框架的客户 端。后来尝试多次发现无法在web project工程中直接生成xfire的客户端。甚至我将独立的一个webservice工程打成jar包发部到web project项目中以无济于事最后让我神经崩溃……一段不到一百行的代码解救了我,不用引jar包,不借助任何框架。自己封装,纯天然纯绿色。
webservice客户端封装类:
public class ServiceUtil {
public static String getRequest(String param, String urls, String soapAction) {
try {
if (param == null || urls == null || soapAction == null) {
return null;
}
URL url = new URL(urls);
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(param
.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("SOAPAction", "\"" + soapAction + "\"");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
osw.write(param);
osw.flush();
osw.close();
InputStream input = conn.getInputStream();
InputStreamReader read = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(read);
StringBuffer buf = new StringBuffer();
while (reader.read() > 0) {
buf.append(reader.readLine());
}
String xmlStr = buf.toString();
input.close();
read.close();
reader.close();
return xmlStr;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
web项目中的action类调用webservice客户端接口:
/**
* 修改客户信息
*
* @return
*/
public String update() {
String param = "<?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:Body><ModifyCustWS xmlns=\"http://www.bocim.com\"> <c> <sFuncFlag>83</sFuncFlag><sAcco></sAcco> <sAccoType></sAccoType> "
+ "<sCustType>1</sCustType> "
+ "<sIDType></sIDType> <sFrom></sFrom> <sOperator></sOperator> <sReserve></sReserve> "
+ "<sAddress>"
+ cust.getAddress()
+ "</sAddress> "
+ "<sZipcode> </sZipcode> "
+ "<sPhone>"
+ cust.getPhone1()
+ "</sPhone> "
+ "<sFaxNo></sFaxNo> "
+ "<sEmail>"
+ cust.getEmail()
+ "</sEmail> "
+ "<sMobileNo>"
+ cust.getMobile1()
+ "</sMobileNo> <sBP></sBP> <sBirthday></sBirthday> <sSex></sSex> <sEducation></sEducation> <sFamilyNo></sFamilyNo><sVocation></sVocation><sIncome></sIncome><sCorpTel></sCorpTel><sCorpName></sCorpName><sBillSend></sBillSend><sHomePhone></sHomePhone><sNationality></sNationality><sBillSendPass></sBillSendPass><sBillSendFlag></sBillSendFlag><sMemo></sMemo><sContact></sContact><sReserve4></sReserve4></c></ModifyCustWS></soap:Body></soap:Envelope>";
String retur = ServiceUtil.getRequest(param, "http://18.1.6.76/BocimWebService/service.asmx", "http://www.bocim.com/ModifyCustWS");
if (retur.indexOf("<sSuccessFlag>0</sSuccessFlag>") == -1) {
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa");
return ActionSupport.INPUT;
}else {
return ActionSupport.SUCCESS;
}
}