如何通过HTTP发送SOAP请求在Java(或C#)中使用摘要身份验证HTTP?

如何通过HTTP发送SOAP请求在Java(或C#)中使用摘要身份验证HTTP?,java,xml,soap,wsdl,digest-authentication,Java,Xml,Soap,Wsdl,Digest Authentication,我有一个url为 此web服务器使用摘要身份验证,用户名为admin,密码为admin 我想将请求跟踪发送到此服务器 SOAP请求XML是SOAP_RQ.XML <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:log="LogsGet" xmlns:mal="MalteseGlobal" xmlns:job="JobGlobal"> <

我有一个url为
此web服务器使用摘要身份验证,用户名为admin,密码为admin
我想将请求跟踪发送到此服务器

SOAP请求XML是SOAP_RQ.XML

 <soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:log="LogsGet" xmlns:mal="MalteseGlobal" xmlns:job="JobGlobal">
         <soapenv:Body>
             <log:LogsGetReq Cmd="Start" OpV="01.00.00" Sev="Info to critical"/>
          </soapenv:Body>
</soapenv:Envelope>     
当我发送请求时,我收到以下消息: 错误响应:(401需要授权)

如果我发送请求,请使用curl工具()和 命令行:curl.exe-X POST-H“内容类型:text/xml;charset=utf-8”-H“SOAPAction:LogsGet”--摘要-u admin:admin-d@SOAP\u RQ.xml-v
我收到了回复OK的信息

有谁能帮助我,如何使用JAVA(或C#)通过HTTP发送SOAP请求

如果使用C#
我创建了成功的
我的代码:

私有字符串WebServiceCall(字符串url)
{
尝试
{
urimyurl=新的Uri(url);
WebRequest WebRequest=WebRequest.Create(myUrl);
HttpWebRequest HttpWebRequest=(HttpWebRequest)webRequest;
httpWebRequest.Method=“POST”;
httpWebRequest.ContentType=“text/xml;charset=utf-8”;
httpWebRequest.Headers.Add(“SOAPAction:LogsGet”);
httpWebRequest.ProtocolVersion=HttpVersion.Version11;
//证书
NetworkCredential myNetworkCredential=新的网络凭据(“管理员”、“管理员”);
CredentialCache myCredentialCache=新的CredentialCache();
添加(myUrl,“摘要”,myNetworkCredential);
httpWebRequest.PreAuthenticate=true;
httpWebRequest.Credentials=myNetworkCredential;
Stream requestStream=httpWebRequest.GetRequestStream();
//创建流并完成请求
StreamWriter StreamWriter=新的StreamWriter(requestStream,Encoding.ASCII);
StringBuilder soapRequest=新的StringBuilder(“”);
soapRequest.Append(“”);
soapRequest.Append(“”);
soapRequest.Append(“”);
streamWriter.Write(soapRequest.ToString());
streamWriter.Close();
//得到回应
txtRequest.Text=soapRequest.ToString();
HttpWebResponse wr=(HttpWebResponse)httpWebRequest.GetResponse();
StreamReader srd=新的StreamReader(wr.GetResponseStream());
字符串resultXmlFromWebService=srd.ReadToEnd();
返回结果xmlfromWebService;
}
捕获(例外e)
{
返回e.ToString();
}
}
//我使用了ApacheHttpClient。
//对于URL,您需要找到端点URL。
导入org.apache.http.auth.AuthScope;
导入org.apache.http.auth.UsernamePasswordCredentials;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.StringEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入java.io.PrintWriter;
导入java.io.StringWriter;
//输入参数
字符串username=“”;
字符串密码=”;
字符串url=“”;
//变数
int-responseCode=0;
字符串errorMessage=“”;
字符串responseContent=“”;
String content=“”
HttpResponse响应;
尝试
{
内容=
"" + 
“\n”+
“\n”+
“\n”+
“\n”;
//创建POST对象并添加参数
HttpPost HttpPost=新的HttpPost(url);
addHeader(“内容类型”,“text/xml;charset=utf-8”);
//在HttpClient内启用抢占式身份验证,以便HttpClient
//在服务器发出未经授权的响应之前发送基本身份验证响应。
字符串host=httpPost.getURI().getHost();
int-port=httpPost.getURI().getPort();
AuthScope AuthScope=新的AuthScope(主机、端口);
DefaultHttpClient httpClient=新的DefaultHttpClient();
UsernamePasswordCredentials凭据=新的UsernamePasswordCredentials(用户名、密码);
httpClient.getCredentialsProvider().setCredentials(authScope,credentials);
StringEntity输入=新的StringEntity(内容);
setContentType(“应用程序/json”);
httpPost.setEntity(输入);
response=httpClient.execute(httpPost);
if(response!=null&&response.getStatusLine()!=null)
{
responseCode=response.getStatusLine().getStatusCode();
responseContent=EntityUtils.toString(response.getEntity());
}
System.out.println(“\n\n----------------------------------------------------”;
System.out.println(“\n响应代码:“+responseCode”);
System.out.println(“\n响应内容:“+响应内容”);
}
捕获(例外e)
{
errorMessage+=“\n意外异常:”+e.getMessage();
StringWriter sWriter=新StringWriter();
PrintWriter pWriter=新的PrintWriter(sWriter,true);
e、 printStackTrace(pWriter);
errorMessage+=“\n”+sWriter.getBuffer().toString();
errorMessage+=“\n--------------错误详细信息----------”;
errorMessage+=“\n”+e;
errorMessage+=“\n”+e.getMessage();
errorMessage+=“\n”+e.getLocalizedMessage();
errorMessage+=“\n”+e.getCause();
errorMessage+=“\n”+Arrays.toString(例如getStackTrace());
errorMessage+=“\n”+e.printStackTrace();
errorMessage+=“\n----------------------------------------------------”;
}
最后
{
如果(答复)
{
使用(response.getEntity());
}
}
如果(errorMessage!=“”)
{
System.out.println(“错误:+errorMessage”);
} 

如果您可以使用Java编写代码,您可以在此toppic上发布。
 private static SOAPMessage createSOAPRequest(String username, String password) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("log", "LogsGet");
        envelope.addNamespaceDeclaration("mal", "MalteseGlobal");
        envelope.addNamespaceDeclaration("job", "JobGlobal");
        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("LogsGetReq", "log");
        QName Cmd = new QName("Cmd");
        QName OpV = new QName("OpV");
        QName Sev = new QName("Sev");
        soapBodyElem.addAttribute(Cmd, "Start");
        soapBodyElem.addAttribute(OpV, "01.00.00");
        soapBodyElem.addAttribute(Sev, "Info to critical");
        //SOAP Header
        MimeHeaders hd = soapMessage.getMimeHeaders();
        hd.addHeader("UsernameToken", username);
        hd.addHeader("PasswordText", password);

        soapMessage.saveChanges();       
        return soapMessage;
    }

public void sendSoapRequest(String url, String username, String password) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server         
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(username, password, txtArea), url);
            // Process the SOAP Response               
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            soapResponse.writeTo(bos);
            System.out.println();  
            soapConnection.close();

        } catch (Exception e) {
            System.out.println("Error occurred while sending SOAP Request to Server");              
            e.printStackTrace();
        }
    }
private  string WebServiceCall(string url)
        {
            try
            {
                Uri myUrl = new Uri(url);
                WebRequest webRequest = WebRequest.Create(myUrl);
                HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "text/xml; charset=utf-8";
                httpWebRequest.Headers.Add("SOAPAction: LogsGet");
                httpWebRequest.ProtocolVersion = HttpVersion.Version11;

                //Credentials
                NetworkCredential myNetworkCredential = new NetworkCredential("admin", "admin");
                CredentialCache myCredentialCache = new CredentialCache();
                myCredentialCache.Add(myUrl, "Digest", myNetworkCredential);
                httpWebRequest.PreAuthenticate = true;
                httpWebRequest.Credentials = myNetworkCredential;
                Stream requestStream = httpWebRequest.GetRequestStream();
                //Create Stream and Complete Request             
                StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

                StringBuilder soapRequest = new StringBuilder("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
                soapRequest.Append("xmlns:log=\"LogsGet\" xmlns:mal=\"MalteseGlobal\" xmlns:job=\"JobGlobal\">");
                soapRequest.Append("<soapenv:Body>");
                soapRequest.Append("<log:LogsGetReq Cmd=\"Start\" OpV=\"01.00.00\" Sev=\"Info to critical\"/>");
                soapRequest.Append("</soapenv:Body></soapenv:Envelope>");

                streamWriter.Write(soapRequest.ToString());
                streamWriter.Close();
                //Get the Response    
                txtRequest.Text = soapRequest.ToString();
                HttpWebResponse wr = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader srd = new StreamReader(wr.GetResponseStream());
                string resulXmlFromWebService = srd.ReadToEnd();
                return resulXmlFromWebService;
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
// I used Apache HttpClient.
// For URL, you need to find end point URL.
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.PrintWriter;
import java.io.StringWriter;

// Input parameter
String username = "";
String password = "";
String url = "";

// Variables 
int responseCode = 0;
String errorMessage = "";
String responseContent = "";
String content = ""

HttpResponse response;

try
{
    content = 
        "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:log=\"LogsGet\" xmlns:mal=\"MalteseGlobal\" xmlns:job=\"JobGlobal\">" + 
        "\n  <soapenv:Body>" +
        "\n    <log:LogsGetReq Cmd=\"Start\" OpV=\"01.00.00\" Sev=\"Info to critical\"/>" + 
        "\n  </soapenv:Body>" +
        "\n</soapenv:Envelope>";

    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "text/xml; charset=utf-8");

    // Enable preemptive authentication within HttpClient so that HttpClient will 
    // send the basic authentications reponse before the server gives an unauthorized reponse. 
    String host = httpPost.getURI().getHost();
    int port = httpPost.getURI().getPort();   
    AuthScope authScope = new AuthScope(host, port);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    UsernamePasswordCredentials credentials = new     UsernamePasswordCredentials(username, password);
    httpClient.getCredentialsProvider().setCredentials(authScope, credentials);   

    StringEntity input = new StringEntity(content);
    input.setContentType("application/json");
    httpPost.setEntity(input);   
    response = httpClient.execute(httpPost);

    if (response != null && response.getStatusLine() != null)
    {
        responseCode = response.getStatusLine().getStatusCode();
        responseContent = EntityUtils.toString(response.getEntity());
    }

    System.out.println("\n\n-----------------------------");
    System.out.println("\nResponse code: " + responseCode);
    System.out.println("\nResponse content: " + responseContent);
}
catch (Exception e)
{
    errorMessage  += "\nUnexpected Exception: " + e.getMessage();
    StringWriter sWriter = new StringWriter();
    PrintWriter pWriter = new PrintWriter(sWriter, true);
    e.printStackTrace(pWriter);
    errorMessage += "\n" + sWriter.getBuffer().toString();

    errorMessage += "\n------------Error Detail------------";
    errorMessage += "\n" + e;
    errorMessage += "\n" + e.getMessage();
    errorMessage += "\n" + e.getLocalizedMessage();
    errorMessage += "\n" + e.getCause();
    errorMessage += "\n" + Arrays.toString(e.getStackTrace());
    errorMessage += "\n" + e.printStackTrace();
    errorMessage += "\n------------------------------------";
}
finally
{
    if(response)
    {
        EntityUtils.consume(response.getEntity());    
    }
}

if(errorMessage != "")
{
    System.out.println("Error: " + errorMessage);
}