我只是想从POST请求中获取REST-API响应。
出现此错误:
如果设置ContentLength> 0或,则必须提供请求正文 SendChunked ==真。通过之前调用[Begin] GetRequestStream来完成此操作 [开始]的GetResponse
这是我的代码:
public enum httpVerb
{
GET,
POST,
PUT,
DELETE
}
class RestProvider
{
public string uri { get; set; }
public httpVerb httpMethod { get; set; }
public RestProvider()
{
uri = "";
httpMethod = httpVerb.POST;
}
public string makeRequest()
{
string strResponseValue = string.Empty;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = httpMethod.ToString();
request.ContentLength = uri.Length;
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
strResponseValue = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
finally
{
if (response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
有什么想法吗?
答案 0 :(得分:1)
这:request.ContentLength = uri.Length;
错了。这不是ContentLength
的用途。单独留下ContentLength
,(在这种情况下它将为零),或发送一些请求内容并将ContentLength
设置为您要发送的请求内容的长度。 uri
不是请求内容。