使用Spring Web服务

时间:2018-03-10 16:55:52

标签: java spring spring-mvc spring-ws

我正在使用Spring,我尝试在soap消息中发送两个参数,第一个参数是我要发送令牌的标头,第二个参数是我在哪里的身体发送固定参数(外观)。

  • " HEADER" 123456789asdfghjkl" HEADER" (那是令牌)
  • " BODY" facadeMethod" BODY"

    我无法使用我的Java代码从客户Web服务获得答案。我已经尝试过使用SOAPUI进行一些测试,并且当我使用SOAPUI时,我总是得到一个结果(我将把示例放在最后一节)。

我有一个"主要"我要发送肥皂信息的类,用两个参数注入spring bean。



@Component
public class CustomerService {	
	
	private WebServiceTemplate webServiceTemplate;

@Autowired
    public void CustomerService(WebServiceTemplate webServiceTemplate) {
        this.webServiceTemplate = webServiceTemplate;
    }
	
	public String sendMyToken(String token) {
		tokenGETSessionLogged logear = new tokenGETSessionLogged();
		
		String exit= "sendMyToken(String token)";
		
		
		final String soapAction = "http://www.CustomerCompany.com/webService/Direction/OfTheWebService/Security/Method/forLogging/withToken/tokenGETSessionLogged";
		
		URI uri1=null;
		
		
		
		
		
		String uri="http://myCompanyURI.org/WebService/ToLoggin/Listen_To_Client_Request/";
		
		HttpComponentsMessageSender mySender = new HttpComponentsMessageSender();
		
		mySender.setConnectionTimeout(800000);
		
		try {
			uri1 = new URI ("http://myCompanyURI.org/WebService/ToLoggin/Listen_To_Client_Request/");
			mySender.createConnection(uri1);
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
		
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
		
		try {
			
			
			webServiceTemplate.setMessageSender(mySender);
			
		}catch(Exception e) {
			
		}
		
		try {
			
			
			logear.setFacade("FacadeSecuritymethod");
			
			
			String headYBody=token + logear.getFacade();
			tokenGETSessionLogged answer= (tokenGETSessionLogged)webServiceTemplate.marshalSendAndReceive(uri, headYBody, new SoapActionCallback(soapAction));
		
			 exit= exit+ answer.toString();
			
		}catch (WebServiceTransportException ex) {
			
		}
		return exit;
	}

}




我在其他类中声明了我的bean变量:



public class ClientApp {


	@Bean
	public Jaxb2Marshaller marshaller() {
		Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
		marshaller.setContextPath("com.xx.soap.model");
		return marshaller;
	}
@Bean
    public WebServiceTemplate webServiceTemplate() throws Exception {

        WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
        webServiceTemplate.setMarshaller(marshaller());
        webServiceTemplate.setUnmarshaller(marshaller());
        webServiceTemplate.setDefaultUri(
                "http://myCompanyURI.org/WebService/ToLoggin/Listen_To_Client_Request/");
        webServiceTemplate.setMessageSender(httpComponentsMessageSender());
        return webServiceTemplate;
    }


@Bean
public HttpComponentsMessageSender httpComponentsMessageSender() throws Exception {
  HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
  httpComponentsMessageSender.setHttpClient(httpClient());
 

  return httpComponentsMessageSender;
}
public HttpClient httpClient() throws Exception {
	HttpClient cl= HttpClients.createDefault();
	
	return cl;
      
  }


}




有人可以告诉我,我做错了什么吗?

我当然检查过很多来源,但没有帮助我发送尸体和标题:

Spring Web Service Template: Add username token

https://www.codenotfound.com/spring-ws-https-client-server-example.html

以防万一我想发一个我发送的SOAPUI消息的例子。我真正想要的是用Java来模拟这个,这不应该那么困难:



<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.CustomerCompany.com/webService/Direction/OfTheWebService/Security/Method/forLogging/withToken/tokenGETSessionL">
   <soapenv:Header>
      <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">                                         
      <wsse:BinarySecurityToken>1234exampleoftokenIWantToSend789045678456cvbty</wsse:BinarySecurityToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <v1:tokenGETSessionLogged facade="FacadeSecuritymethod"/>
   </soapenv:Body>
</soapenv:Envelope>
&#13;
&#13;
&#13;

我不擅长发帖,但我会尽力解释我是如何解决的。

首先你需要的是一个webInitializer类,以告诉你的服务正确调用你的spring bean创建的Controller。

&#13;
&#13;
public class WebInitializer implements WebApplicationInitializer {
    
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {        
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();  
        context.register(Config.class);  
        context.setServletContext(servletContext);    
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));  
        servlet.addMapping("/authentication");  
        servlet.setLoadOnStartup(1);
    }
   
}
&#13;
&#13;
&#13;

默认控制器或Controller类是您必须创建对象的位置,您将使用标题和正文构建整个消息。 如您所见,将使用参数身份验证

标识该类

&#13;
&#13;
@Controller
public class DefaultController {
    /** The Constant LOG. */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(DefaultController.class);
    
    @Autowired
    private SoapService messageservice ;
    
   @RequestMapping(value = "/authentication", method = RequestMethod.GET)
   public String index(ModelMap map, @RequestParam(value="token") String token) {
	   Properties prop= new Properties(); 
	   String back= "MESSAGESERVICE";
	   Book myLog=null;
       String pathLog= " ";
       try {
	   //declare a new log file 
    	   pathLog=System.getProperty("catalina.home");
    	   pathLog=pathLog+"config.properties";// I saved a config file where I set the place where I set the trace file for the log
    	   prop.load(new FileReader(pathLog));
    	   String path = new File(".").getCanonicalPath();//this file is not relevant for this example but maybe help you
    	   
    	   path=prop.getProperty("LOGGERPATH");
    	   pathLog=path;
    	   myLog= new Book(pathLog);
    	   myLog.logger.warning("Starting the SOAP operation for send Spring message");
    	   
           Input input = new Input();;
           input.setToken(token);
           
           String name="empty";
           name=token;
          
           
           
           GetLoggedUIDResponse s = messageservice.SendMSG(input,  myLog);//here I call my message constructor method
           String k=s.getMethodResult();
           myLog.logger.warning("Result of operation "+k);
           
          
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		back="message";
	}
       
       
       
       return back;
   }
    
}
&#13;
&#13;
&#13;

在本课程中,我将调用SendMSG方法,我将构建整个消息。 (身体+标题)。这个方法将调用一个新类,我将在其中创建我的Web服务需要重用的SOAP消息(messageservice.SendMSG)

我有另一个class(),其中创建了SendMSG方法。

&#13;
&#13;
@Component
public class MessageServiceSOAP extends WebServiceGatewaySupport {

 
    
	
	private WebServiceTemplate webServiceTemplate;

	@Autowired
	public void SmsService(WebServiceTemplate webServiceTemplate) {
		this.webServiceTemplate = webServiceTemplate;
	}

 

	public GetLoggedUIDResponse SendMSG(Input input, Log2Sev myLog) {
		 
		tokenGETSessionLogged  request = new tokenGETSessionLogged ();
		tokenGETSessionLogged Response returnObj = new tokenGETSessionLogged Response();
		

		
		try {
			String soapAction = " ";
			
			String pathLog="";
			Properties p= new Properties(); 
			pathLog=System.getProperty("catalina.home");//properties file where I get my parameters
			pathLog=pathLog+"\\config.properties";
			p.load(new FileReader(pathLog));
	 	   	soapAction="http://www.CustomerCompany.com/webService/Direction/OfTheWebService/Security/Method/forLogging/withToken/tokenGETSessionLogged";
			HttpComponentsMessageSender sender = new HttpComponentsMessageSender();
			sender.setConnectionTimeout(100000);

		
			String myToken=input.getToken();//the token you will use
			
			
			webServiceTemplate.setMessageSender(sender);
			try {
				request.setFacade("ACFACSEGSecurity");

				SoapActionCallback actionCallBack = CallBackSOAPActionBuild(soapAction, myToken);

			
				 returnObj = (tokenGETSessionLogged Response) webServiceTemplate
						.marshalSendAndReceive(request, actionCallBack);

				
				
				return returnObj;
			} catch (WebServiceTransportException ex) {
				
				returnObj.setMethodResult("excepcion transporte");
			} catch (SoapFaultClientException ex) {
				
				returnObj.setMethodResult("excepcion soapCliente");
			}

		} catch (Exception e) {
			e.printStackTrace();
			returnObj.setMethodResult("excepcion");
		}
		
		return returnObj;

	}

	public SoapActionCallback CallBackSOAPActionBuild(final String soapAction, String myToken) {

		SoapActionCallback actionCallBack = new SoapActionCallback(soapAction);
		try {
			actionCallBack = new SoapActionCallback(soapAction) {
				public void doWithMessage(WebServiceMessage msgSend) {
					SoapMessage msgSOAP = (SoapMessage) msgSend;
					SoapHeader soapHeader = msgSOAP.getSoapHeader();

					try {

						;

						// this is the part for the header 
						StringSource headerSource = new StringSource(
								// "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http:URI/From/customer/secutrity/facade">\n" +
								//"<soapenv:Header>\n" +
								 "<wsse:Security xmlns:wsse=\"http://wsSecutirtyFilewithExtension.xsd\">;\n"
								+ "<wsse:BinarySecurityToken>"+ myToken +"</wsse:BinarySecurityToken>\n"
								+ "</wsse:Security>\n"  
								//"</soapenv:Header>"
								);
					
						Transformer trnsfr = TransformerFactory.newInstance().newTransformer();
						transformer.transform(headerSource, soapHeader.getResult());

						msgSOAP.setSoapAction(soapAction);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
		} catch (SoapFaultClientException sfce) {
			sfce.printStackTrace();
		} catch (WebServiceIOException we) {
			we.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return actionCallBack;
	}

}
&#13;
&#13;
&#13;

这里我将创建对象whit头和body参数,这是我的问题所在的主要调用。考虑到我输入了几个虚拟参数,因此这段代码毫无意义,您必须使用客户端将为您提供的参数替换参数。表格示例soapAction,Web服务的URI等。

这里我有一个方法(CallBackSOAPActionBuild),它创建消息的标题,其中myToken被选中以验证Web服务中的用户。将使用uri为.xsd文件以及WS的外观的URI发送用户令牌。

请注意,我已经将代码更改为对于读者来说更简单,因为我的代码具有更多不必要的功能。

0 个答案:

没有答案