在过去的两个星期中,我无法找到解决非常简单的问题的方法。有趣的是,Web服务运行良好。我可以使用WCF客户端调用服务方法。也可以使用SoapUI软件进行访问。
该问题与使用“通过Mtom编码的Web服务”有关。我想通过MIME请求使用网络服务。
WebService实施
我有简单的Web服务以及AddData(int a,int b)函数。
[ServiceContract]
public interface IService1
{
[OperationContract]
int AddData(int i, int j);
}
public class Service1 : IService1
{
public int AddData(int a, int b)
{
return a + b;
}
}
与Web服务的Binding和MessageEncoding分别为BasicHttpBinding和Mtom:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="myBasicHttpBinding" messageEncoding="Mtom" />
</basicHttpBinding>
</bindings>
客户端Web服务消耗 在客户端/使用Web服务的代码如下:
private void webService_AddDataMIME()
{
string endPoint = url;
string boundary = "MIMEBoundaryurn";
string CRLF = "\r\n";
string uuid = System.Guid.NewGuid().ToString();
string reqUUID = System.Guid.NewGuid().ToString();
string attchmtUUID = System.Guid.NewGuid().ToString();
HttpWebResponse httpResp = null;
//Create the HTTP request and set the headers
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Headers.Add("Accept-Encoding: gzip,deflate");
httpRequest.Headers.Add("UserAgent", "Apache-HttpClient");
httpRequest.Headers.Add("MIME-Version", "1.0");
httpRequest.Headers.Add("SOAPAction", @"http://tempuri.org/IService1/AddData");
string ContentType = "multipart/related ; type=\"application/xop+xml\" ;start=\"abcID\"; start-info=\"text/xml\"; boundary=\"" + boundary + "\"";
httpRequest.ContentType = ContentType;
httpRequest.Method = "POST";
string uploadFileRequest = boundary + CRLF
+ "Content-Type:application/xop+xml; charset=UTF-8; type=\"text/xml\" " + CRLF
+ "Content-Transfer-Encoding: 8bit" + CRLF
+ "Content-ID: abcID" + CRLF + CRLF
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/><soapenv:Body><tem:AddData><tem:i>2</tem:i><tem:j>3</tem:j></tem:AddData></soapenv:Body></soapenv:Envelope>"
+ CRLF + boundary + uuid + "--" + CRLF + CRLF;
//Convert the string to a byte array
byte[] postDataBytes1 = System.Text.Encoding.UTF8.GetBytes(uploadFileRequest);
int len = postDataBytes1.Length;
httpRequest.ContentLength = len;
//Post the request
System.IO.Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(postDataBytes1, 0, postDataBytes1.Length);
string response;
// Get response and write to console
try
{
httpResp = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException e)
{
using (WebResponse respons = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)respons;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = respons.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
StreamReader responseReader = new StreamReader(httpResp.GetResponseStream(), Encoding.UTF8);
response = responseReader.ReadToEnd();
httpResp.Close();
Console.WriteLine(response);
}
错误::当我运行客户端代码时,它会返回“错误400:错误的请求”