日期:2014-05-19  浏览次数:20930 次

使用SAAJ发送向WebService发送soap之后,返回的消息中文出现乱码
是这样的,我参考http://www.ibm.com/developerworks/cn/xml/x-jaxmsoap/中的示例,进行测试,由于示例中的WebService不能用,我自己用myEclipse中的JAX-WS框架创建了一个简单的WebService——myFirstWS,myFirstWS对外提供一个sayHello(String name)方法,这个方法返回name+",this is my first Jaxws!". 
  当客户端调用时,当传入的name为中文的时候,在服务器端接受到的参数很正常,不出现乱码,但是返回到客户端的消息中就会出现乱码。具体代码如下: 

import javax.xml.soap.MessageFactory; 
import javax.xml.soap.SOAPBody; 
import javax.xml.soap.SOAPConnection; 
import javax.xml.soap.SOAPConnectionFactory; 
import javax.xml.soap.SOAPElement; 
import javax.xml.soap.SOAPEnvelope; 
import javax.xml.soap.SOAPMessage; 
import javax.xml.soap.SOAPPart; 
import javax.xml.transform.Source; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.stream.StreamResult; 

public class SOAPTip { 
public static void main(String args[]) { 

try { 
// First create the connection 
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance(); 
SOAPConnection connection = soapConnFactory.createConnection(); 

//Next, create the actual message 
  MessageFactory messageFactory = MessageFactory.newInstance(); 
  SOAPMessage message = messageFactory.createMessage(); 
   
  message.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "gb2312"); 

  SOAPPart soapPart = message.getSOAPPart(); 
   
  //Create objects for the message parts  
  SOAPEnvelope envelope = soapPart.getEnvelope(); 
  SOAPBody body = envelope.getBody(); 
   
  //Populate the body 
  //Create the main element and namespace 
  SOAPElement bodyElement = body.addChildElement(envelope.createName("sayHello", "ns1", "http://jaxws.shaw.com/")); 
   
  //Add content 
  String city = "北京"; 
  bodyElement.addChildElement("arg0").addTextNode(city); 
   
  //Save the message 
  message.saveChanges(); 
   
  //Check the input 
  System.out.println("\\nREQUEST:\\n"); 
  message.writeTo(System.out); 
  System.out.println(); 
   
  //Send the message and get a reply  
   
  //Set the destination 
  String destination = "http://localhost:8080/myFirstWS/HelloJaxwsPort?wsdl"; 
  //Send the message 
  SOAPMessage reply = connection.call(message, destination); 
  //Check the output 
  System.out.println("\\nRESPONSE:\\n"); 
  //Create the transformer 
  TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
  Transformer transformer = transformerFactory.newTransformer(); 
  //Extract the content of the reply 
  Source sourceContent = reply.getSOAPPart().getContent(); 
   
  //Set the output for the transformation 
  StreamResult result = new StreamResult(System.out);