java调用自定义参数的webservice,并要求传递用户名和密码

前段时间因为项目需要要调用一个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);

函数描述

上报数字化城管案件。

实体类字段可以参考上面的请求和相应可以得知。

 

在这个过程中实验了三种方法:

第一种就是到网上找,但是总是提示无法实例化注册的类,弄了很久也没有弄好,于是放弃了。(在网上可以找到的)

第二步,就是利用给出的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;  }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/fumingxing/archive/2012/11/01/2750359.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
调用 Java WebService 时也需要提供认证信息。下面是一个使用 Java 调用 WebService 的示例代码,包含了认证信息: ``` import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import com.example.webservice.MyService; import com.example.webservice.MyServicePortType; public class MyWebServiceClient { public static void main(String[] args) { try { // WebService 的 URL URL url = new URL("https://www.example.com/webservice?wsdl"); // WebService 的 QName QName qname = new QName("http://example.com/webservice", "MyService"); // 创建 WebService 客户端 MyService service = new MyService(url, qname); MyServicePortType port = service.getMyServicePort(); // WebService 的认证信息 String username = "your_username"; String password = "your_password"; // 设置认证信息 BindingProvider bindingProvider = (BindingProvider) port; bindingProvider.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username); bindingProvider.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password); // 调用 WebService String result = port.getData("value1", "value2"); // 处理返回的数据 System.out.println("Result: " + result); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用了 Javajavax.xml.ws 包提供的类来创建 WebService 客户端。我们还将用户名密码作为参数传递给 BindingProvider.getRequestContext().put() 方法,以实现身份认证。最后,我们调用 WebService 的方法并处理返回的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值