代码之家  ›  专栏  ›  技术社区  ›  keduadoi

如何使用java在SOAP UI中发送带有用户名和密码的SOAP请求

  •  0
  • keduadoi  · 技术社区  · 7 年前

    很抱歉,如果这个问题重复出现,但我在StackOverflow中尝试了几个解决方案,但仍然无法发送SOAP请求。

    我目前的情况是,我的java应用程序需要向我的客户web服务发送SOAP请求,这是我在SOAP UI中成功完成的,用户名、密码、身份验证类型为:抢先。请看图片

    enter image description here

    现在我想在Java中这样做,我已经创建了SOAP信封,没有设置密码,响应与在SOAP UI中使用无身份验证时完全相同,这意味着Java代码只需要添加身份验证即可工作。 以下是我当前的Java代码:

    callSoapWebService(soapEndpointUrl, soapAction);
    
    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
    
            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
    
            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();
    
            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }
    
    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
    
        createSoapEnvelope(soapMessage);
    
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);
    
        soapMessage.saveChanges();
    
        return soapMessage;
    }
    

    在createSoapEnvelope()中是创建SOAP请求主体的代码,所以我想我必须对头部进行一些处理。任何人都可以像我在SOAP UI中所做的那样帮助我实现身份验证?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Jialzate    7 年前

    您需要以基本格式发送用户名和密码:

    String userAndPassword = String.format("%s:%s",username, password);
    
    String basicAuth = new sun.misc.BASE64Encoder().encode(userAndPassword.getBytes());
    MimeHeaders mimeHeaders = message.getMimeHeaders();
    mimeHeaders.addHeader("Authorization", "Basic " + basicAuth);
    

    如果您使用的是Java 8,请使用 Base64.getEncoder().encodeToString() 而不是 new sun.misc.BASE64Encoder() .