使用HttpWebRequest消耗wcf服务c#

时间:2015-01-20 07:01:19

标签: c# wcf httpwebrequest

HttpWebRequest req = null;
HttpWebResponse res = null;

const string url = http://localhost/MyService/EService.svc/CreateMethod";

req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";

req.Headers.Add("App", "Application");
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes("{ itemlist: 'sasfs' }");
req.ContentLength = data.Length;

res = (HttpWebResponse)req.GetResponse();
Stream responseStream = res.GetResponseStream();
var streamReader = new StreamReader(responseStream);

string txt = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();

responseStream.Close();
responseStream.Dispose();

我必须使用上面的代码来使用服务,但是我得到了不同的错误 - 1)如果设置ContentLength> 0,则必须提供请求正文.... 我在这里错过的代码是什么。

1 个答案:

答案 0 :(得分:1)

您缺少几行代码。您只设置ContentLength但不写内容。

req.ContentLength = data.Length;

//Write request data(setting content of request)
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();

res = (HttpWebResponse)req.GetResponse();