前段时间因为项目需要要调用一个webservice,这个webservice要求传递的参数是一个自定义类型的,第一次用webservice费了很大的力气才搞定。
请求的事例:
POST /PublicService/ASMX/WebSiteService.asmx HTTP/1.1
Host: www.xcszcg.com
Content-Type: text/xml; charset=utf-8
Content-Length: lengthSOAPAction: "http://topevery.org/InsertWXCSReport"
<?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:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://topevery.org/" xmlns:types="http://topevery.org/encodedTypes" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<types:SmsHeader>
<UserID xsi:type="xsd:string">string</UserID> <PassWord xsi:type="xsd:string">string</PassWord> </types:SmsHeader> </soap:Header> <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <tns:InsertWXCSReport> <entity href="#id1" /> </tns:InsertWXCSReport> <types:AcceptParameter id="id1" xsi:type="types:AcceptParameter"> <DbCreateDate xsi:type="xsd:dateTime">dateTime</DbCreateDate> <Position xsi:type="xsd:string">string</Position> <Desc xsi:type="xsd:string">string</Desc> <Summary xsi:type="xsd:string">string</Summary> <Reporter xsi:type="xsd:string">string</Reporter> <TelNum xsi:type="xsd:string">string</TelNum> <IsReceipt xsi:type="xsd:boolean">boolean</IsReceipt> <ReplyWay xsi:type="xsd:string">string</ReplyWay> <ReplyType xsi:type="xsd:unsignedByte">unsignedByte</ReplyType> <DistrictID xmlns:s0="http://microsoft.com/wsdl/types/" xsi:type="s0:guid">guid</DistrictID> <StreetID xmlns:s0="http://microsoft.com/wsdl/types/" xsi:type="s0:guid">guid</StreetID> <CommunityID xmlns:s0="http://microsoft.com/wsdl/types/" xsi:type="s0:guid">guid</CommunityID> </types:AcceptParameter> </soap:Body> </soap:Envelope>
返回事例:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?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:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://topevery.org/" xmlns:types="http://topevery.org/encodedTypes" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:InsertWXCSReportResponse>
<InsertWXCSReportResult href="#id1" />
</tns:InsertWXCSReportResponse>
<types:InsertResult id="id1" xsi:type="types:InsertResult">
<AcceptNo xsi:type="xsd:string">string</AcceptNo>
</types:InsertResult>
</soap:Body>
</soap:Envelope>
厂家接口描述:
public InsertResult InsertSiteReport(AcceptParameter entity);
l 函数描述
上报数字化城管案件。
实体类字段可以参考上面的请求和相应可以得知。
在这个过程中实验了三种方法:
第一种就是到网上找,但是总是提示无法实例化注册的类,弄了很久也没有弄好,于是放弃了。(在网上可以找到的)
第二步,就是利用给出的wsdl用ecplise文件本地化,但是本地化后项目并没有传递用户名和密码的方法,可能是我水平有限吧,最后放弃。(步骤网上有)
第三种,最后被逼无奈了,只好后用最原始的http请求了,先把请求的xml格式用字符串拼起来,然后发送过去,返回的xml有用sax解析,最后决绝乱码问题,最终搞定。
下面附上我的代码,共大家参考。
public class InsertWXCSReportService extends DefaultHandler{
private InsertResult result = null;
private String tagName;
public static void postData(Reader data, URL endpoint, Writer output) throws Exception{
HttpURLConnection urlc = null;
try {
urlc = (HttpURLConnection) endpoint.openConnection();
try {
urlc.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new Exception("Shouldn’t happen: HttpURLConnection doesn’t support POST", e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
OutputStream out = urlc.getOutputStream();
try {
Writer writer = new OutputStreamWriter(out, "UTF-8");
pipe(data, writer);
writer.close();
} catch (IOException e) {
throw new Exception("IOException while posting data", e);
} finally {
if (out != null)
out.close();
}
InputStream in = urlc.getInputStream();
try {
Reader reader = new InputStreamReader(in);
pipe(reader, output);
reader.close();
} catch (IOException e) {
throw new Exception("IOException while reading response", e);
} finally {
if (in != null)
in.close();
}
} catch (IOException e) {
throw new Exception("Connection error (is server running at " + endpoint + "): " + e);
} finally {
if (urlc != null)
urlc.disconnect();
} }
private static void pipe(Reader reader, Writer writer) throws IOException {
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0) {
writer.write(buf, 0, read);
}
writer.flush();
}
public InsertResult getInsertResult(AcceptParameter acceptParameter, InsertWXCSReportService dataCityService){
//这部分是拼字符串
String reqContent= "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" rel="nofollow" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/" + "\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" rel="nofollow" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" rel="nofollow" xmlns:m0=\"http://topevery.org/" + "\" xmlns:m1=\"http://topevery.org/encodedTypes" + "\"><SOAP-ENV:Header><m0:SmsHeader xsi:type=\"m1:SmsHeader\"><UserID xsi:type=\"xsd:string\">admin</UserID>" +"<PassWord xsi:type=\"xsd:string\">admin</PassWord></m0:SmsHeader></SOAP-ENV:Header>" +"<SOAP-ENV:Body><m:InsertWXCSReport xmlns:m=\"http://topevery.org/\" rel="nofollow" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" rel="nofollow">" +"<entity xsi:type=\"m1:AcceptParameter\">" + "<DbCreateDate xsi:type=\"xsd:dateTime\">"+acceptParameter.getDbCreateDate()+"</DbCreateDate>" + "<Position xsi:type=\"xsd:string\">"+acceptParameter.getPosition()+"</Position>" + "<Desc xsi:type=\"xsd:string\">"+acceptParameter.getDesc()+"</Desc>" + "<Summary xsi:type=\"xsd:string\">"+acceptParameter.getSummary()+"</Summary>" + "<Reporter xsi:type=\"xsd:string\">"+acceptParameter.getReporter()+"</Reporter>" + "<TelNum xsi:type=\"xsd:string\">"+acceptParameter.getTelNum()+"</TelNum>" + "<IsReceipt xsi:type=\"xsd:boolean\">"+acceptParameter.getIsReceipt()+"</IsReceipt>" + "<ReplyWay xsi:type=\"xsd:string\">"+acceptParameter.getReplyWay()+"</ReplyWay>" + "<ReplyType xsi:type=\"xsd:unsignedByte\">"+255+"</ReplyType>" + "</entity></m:InsertWXCSReport></SOAP-ENV:Body></SOAP-ENV:Envelope>";
System.out.println(".....xml....req.."+reqContent);
try {
Reader reader = new InputStreamReader(new ByteArrayInputStream(reqContent.getBytes()));
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
Writer out = new OutputStreamWriter(byteOut);
//DataCtiyService poster = new DataCtiyService();
this.postData(reader, new URL("http://www.xxxxxxx.xxxxxxx/ASMX/WebSiteService.asmx"), out);
System.out.println("............string...."+byteOut.toString());
if(byteOut.toString().length()>0){
SAXParser parser = null;
parser = SAXParserFactory.newInstance().newSAXParser();
//DataCityService dataCityService = new DataCityService();
InputStream xmlInputRes = new ByteArrayInputStream(byteOut.toString().getBytes());
parser.parse(xmlInputRes, dataCityService);
System.out.println(".......返回的结果......"+this.result.getAcceptNo());
} } catch (Exception e) {
// TODO Auto-generated catch block e.printStackTrace(); }
return result; }
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if(this.tagName!=null){
String data = new String(ch,start,length);
if("IsSuccess".equals(this.tagName)){
System.out.println("....isSuccess......"+data);
this.result.setIsSuccess(data+"");
}
if("AcceptNo".equals(this.tagName)){
System.out.println("....AcceptNo......"+data);
this.result.setAcceptNo(data);
}
if("ErrorMsg".equals(this.tagName)){
System.out.println("....ErrorMsg......"+data); this.result.setErrorMsg(data); } } }
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(qName.equals("types:InsertResult")){
this.result = new InsertResult();
}
this.tagName=qName;
}
public InsertResult getResult() {
return result;
}
public void setResult(InsertResult result) { this.result = result; }
public String getTagName() { return tagName; }
public void setTagName(String tagName) { this.tagName = tagName; }
}