我必须使用提供的 Java Web 服务。但问题是此服务需要自定义 HTTPHeaders。我已经寻找解决方案。如果我可以添加参考,我认为这个会起作用。但是当我尝试添加对服务的引用时,出现以下错误:
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 提供的这个解决方案,并添加了如下自定义标头:
// 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 消息,并将结果作为解析的对象。有什么解决方法吗?提前致谢。