我需要调用以下REST API
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/{subscriptionId}/servers?op=ChangeSubscription")]
Stream ChangeAllServersSubscription(string subscriptionId, Stream requestStream);
如何创建并传递Stream requestStream
?流将包含JSON格式的字符串
在使用任何类型的Stream
之前,您应该询问API供应商他希望接收哪个流。
下面是一个使用MemoryStream
的例子,在您创建JSON之后:
// Random objects, just to make the code clear
var myObject = new {Name = "Yakov"};
var myId = "1";
var myJson = JsonConvert.SerializeObject(myObject);
// Create a MemoryStream (Encoding should be as needed)
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(myJson));
// Call your code
var responseStream = ChangeAllServersSubscription(myId, memoryStream);
// And dispose the MemoryStream after you're done.
memoryStream.Dispose();
您可以在客户端创建一个HttpWebRequest
,设置url指向您的服务,设置适当的方法-在您的情况下POST
。例如:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://server/id/servers?op=ChangeSubscription");
request.Method = "POST";
然后使用GetRequestStream()
在客户端获取流,将json写入该流,关闭流,然后通过调用GetResponse()
执行请求。
Stream stream= request.GetRequestStream();
//stream.Write write contents of your file here!
stream.Close();
HttpWebResponse response= (HttpWebResponse)request.GetResponse();
//process the response from server
如果一切正常,你的web服务将会收到你的文件。