【问题标题】:How to send SOAP request with username and password like in SOAP UI using java如何使用 java 的 SOAP UI 发送带有用户名和密码的 SOAP 请求
【发布时间】:2017-12-24 00:45:10
【问题描述】:

对不起,如果这个问题重复了,但我在 StackOverflow 中尝试了几个解决方案,但仍然遇到发送 SOAP 请求的问题。

我目前的情况是我的 java 应用程序需要向我的客户 Web 服务发送 SOAP 请求,我在 SOAP UI 中成功地使用了用户名、密码、身份验证类型:抢占式。请看图

现在我想用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 中那样帮助我实现身份验证吗?

【问题讨论】:

    标签: java soap http-headers soapui basic-authentication


    【解决方案1】:

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

    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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2018-04-16
      相关资源
      最近更新 更多