如何将xml字符串发送到套接字连接

时间:2013-11-26 13:14:16

标签: java xml sockets jaxb

我有一个多复杂的xml字符串,我想通过TCP / IP套接字连接发送它,但我似乎不知道是否写入字符串,当我telnet到服务器并发送请求我得到一个正确的响应,但我想实现一个socket类来发送请求和jaxb来解析我的对象类到xml。下面是代码

  Estel es = new Estel();
  Header hd = new Header();
  Request rq = new Request();
  hd.setRequestType("TOPUP");
  es.setHeader(hd);
  es.setRequest(rq);
  rq.setAgentCode("8033818446");
  rq.setPin("44B7A065BC937DE9406EABD6AB162AD4");
  rq.setDestination("08033818446");
  rq.setAgentTransId("20130618211503000021");
  rq.setVendorCode("CHIT");
  rq.setAmount(100);
  rq.setProductCode("MTNTOP");
  rq.setClientType("pc");
  rq.setComments("testing e top up");


 //JAXB mashalls the object to xml form 
 JAXBContext jaxb  = JAXBContext.newInstance(Estel.class);
 Marshaller msh = jaxb.createMarshaller();
 msh.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
  StringWriter str = new StringWriter();
 msh.marshal(es, str);


  //what the marshalled string looks like 
  /*<estel><header><requesttype>TOPUP</requesttype></header><request>  
  <agentcode>8033818446</agentcode><pin>44B7A065BC937DE9406EABD6AB162AD4</pin> 
  <destination>08033818446</destination>
  <agenttransid>20130618211503000021</agenttransid><vendorcode>CHIT</vendorcode>
  <amount>100</amount><productcode>MTNTOP</productcode><comments>Powered by ReadyCash Mobile Money</comments><clienttype>PC</clienttype></request>
  </estel> */


Socket soc = new Socket("41.206.23.21",7101);

OutputStream os =    soc.getOutputStream(); 
os.write(str.toString().getBytes());
os.flush();

soc.shutdownOutput();


 //Read input stream and unmarshall to object

    InputStream input = soc.getInputStream();

    Unmarshaller unmarshaller = jaxb.createUnmarshaller();

 System.out.print("\n--------passing---------"); 


Estel estel = (Estel)unmarshaller.unmarshal(input);
System.out.print("\n--------reading---------"); 
System.out.print("\nheader is "+estel.getHeader().getResponseType());
System.out.print("\ncode is"+estel.getResponse().getAgentCode());

os.close();
input.close();
soc.close();

我不知道我是否正在写这个东西,当我发送它时,我在xml体中得到无效请求意味着我没有发送正确的格式,在JAXB中将xml编组发送到Socket服务器的正确方法是什么

0 个答案:

没有答案
相关问题