无法添加对现有服务的引用。服务所需的HTTP标头

时间:2013-02-01 12:40:58

标签: c# soap service http-headers

我必须使用提供的Java Web服务。但问题是此服务需要自定义HTTPHeader。我一直在寻找解决方案。如果我可以添加引用,我认为this one会起作用。但是当我尝试添加对服务的引用时,我收到以下错误:

There was an error downloading 'http://.....'.
The request failed with HTTP status 400: Bad Request.
Metadata contains a reference that cannot be resolved: 'http://......'.
The remote server returned an unexpected response: (400) Bad Request.
The remote server returned an error: (400) Bad Request.
If the service is defined in the current solution, try building the solution and adding    the service reference again.

我认为安全服务器不允许我访问元数据。 我在MSDN上尝试了this solution并添加了如下所示的自定义标题:

    // Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create("http://....");
    // Set the Method property of the request to POST.
    request.Method = "POST";
    // Create POST data and convert it to a byte array.

    string postData = string.Empty;
    using (StreamReader contentReader = new StreamReader("D:\\test.txt"))
    {
        postData = contentReader.ReadToEnd();
    }

    //Add headers to request
    request.Headers.Add("UserName", "myUserName");
    request.Headers.Add("Password", "myPassword");
    request.Headers.Add("SomeCustomHeader", "myCustomHeaderValue");

    //string postData = "This is a test that posts this string to a Web server.";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    // Set the ContentType property of the WebRequest.
    request.ContentType = "text/xml";
    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    // Get the request stream.
    Stream dataStream = request.GetRequestStream();
    // Write the data to the request stream.
    dataStream.Write(byteArray, 0, byteArray.Length);
    // Close the Stream object.
    dataStream.Close();
    // Get the response.
    WebResponse response = request.GetResponse();
    // Display the status.
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    // Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd();


    using (StreamWriter resultWriter = new StreamWriter("D:\\result.xml"))
    {
        resultWriter.Write(responseFromServer);
    }

    // Display the content.
    //Console.WriteLine(responseFromServer);
    // Clean up the streams.
    reader.Close();
    dataStream.Close();
    response.Close();

    Console.ReadLine();

它对我有用。我现在可以从服务获得结果(作为xml文件),我也有WSDL。所以我想我可以将这个结果解析为适当的对象。但我希望能够添加服务引用并像普通服务一样使用它。我的意思是用他们的名字调用方法,不使用SOAP消息,并将结果作为解析对象。 有没有解决方法?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用wsdl.exe工具创建代理类。看看http://msdn.microsoft.com/en-us/library/aa529578.aspx