我在.NET中创建了一个基本的RESTful服务,允许我对调用方法指定的Uri进行基本的Get和Post调用。在我的post方法中,我试图用我的HttpWebRequest调用GetRequestStream,但是我得到一个ProtocolViolationException,消息“无法使用此动词类型发送内容体。”
我知道这可能是由于HttpWebRequest方法设置为Get,但是我已经调试并确保在进行GetRequestStream调用时该方法是Post。我无法弄清楚为什么会被扔掉。谁能帮我吗?代码在下面
public HttpWebResponse Get(bool followRedirect = true)
{
_webRequest.Method = WebRequestMethods.Http.Get;
_webRequest.AllowAutoRedirect = followRedirect;
_webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var webResponse = _webRequest.GetResponse() as HttpWebResponse;
_webRequest.CookieContainer.Add(webResponse.Cookies);
return webResponse;
}
public HttpWebResponse Post(string contentType, Dictionary<String,String> parameters, bool followRedirect = true)
{
_webRequest.Method = WebRequestMethods.Http.Post;
_webRequest.AllowAutoRedirect = followRedirect;
var postData = "";
foreach (var parameter in parameters)
{
postData += HttpUtility.UrlEncode(parameter.Key) + "=" +
HttpUtility.UrlEncode((parameter.Value)) + "&";
}
postData = postData.Remove(postData.Length - 1, 0);
var data = Encoding.UTF8.GetBytes(postData);
_webRequest.ContentType = contentType;
var requestStream = _webRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
var webResponse = _webRequest.GetResponse() as HttpWebResponse;
return webResponse;
}
我发现问题是由调用_webRequest.GetResponse()引起的,然后我使用相同的_webRequest来调用GetRequestStream()。这种行为有望吗?也就是说,WebRequest是否只能在需要重新初始化/重置之前进行其中一个调用?
我通过基本上在Post中创建一个新的WebRequest并将_webRequest中的值复制到它来进行修复,但我想知道是否有必要或者是否有更强大的解决方案。
答案 0 :(得分:1)
好的,所以我意识到这个问题来自于调用_webRequest.GetResponse()然后使用相同的WebRequest调用.GetRequestStream()。不确定为什么会这样,但这就是导致问题的原因。我通过创建一个新的WebRequest并将相关属性复制到新的Request来解决这个问题。
答案 1 :(得分:0)
如果您没有特定的类型或内容,请不要在标题上发送内容类型。
例如获取flickr基本请求/ json响应
var baseUrl = string.Format("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&format=json&nojsoncallback=1", flickrApiKey);
HttpWebRequest httpRequest = HttpWebRequest.Create(baseUrl) as HttpWebRequest;
httpRequest.BeginGetResponse(GetResponseStream, httpRequest);
async void GetResponseStream(IAsyncResult callbackResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
string responseString = string.Empty;
Stream streamResponse = response.GetResponseStream();
StreamReader reader = new StreamReader(streamResponse);
responseString = reader.ReadToEnd();
}
catch (ProtocolViolationException ex)
{
MessageDialog show = new MessageDialog("no internet connection available");
}
catch (Exception e)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.Run Async(CoreDispatcherPriority.Normal, async () =>
{
MessageDialog show = new MessageDialog("something went wrong");
await show.ShowAsync();
});
}
}