0

我正在尝试创建一个将 url 作为参数并从中返回 GET Response 的函数,它只是在该WebResponse responseObject intialization行中给我一个错误

例外是An exception of type 'System.Net.ProtocolViolationException' occurred in mscorlib.ni.dll but was not handled in user code

public static async Task<string> get(string url)
{
    var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
    request.Method = "GET";
    request.ContentType = "application/json";
    WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
    var responseStream = responseObject.GetResponseStream();
    var sr = new StreamReader(responseStream);
    string received = await sr.ReadToEndAsync();

    return received;
}
4

2 回答 2

6

您无法设置ContentTypeGET 请求,因为您没有将任何数据发送到服务器。

Content-Type = 请求正文的 MIME 类型(用于 POST 和 PUT 请求)。

这是您的ProtocolViolationException.

看起来您想设置Accept标题。

Accept = 响应可接受的内容类型

(根据维基百科

尝试将您的代码更改为:

request.Accept = "application/json";
于 2013-05-14T15:32:30.800 回答
2

尝试使用 HttpClient 代替,如下所示:

    public async Task<List<MyClass>> GetMyClassAsync(
    CancellationToken cancelToken = default(CancellationToken))
    {
        using (HttpClient httpClient = new HttpClient())
        {
            var uri = Util.getServiceUri("myservice");
            var response = await httpClient.GetAsync(uri, cancelToken);
            return (await response.Content.ReadAsAsync<List<MyClass>>());
        }
    }
于 2013-05-14T13:46:57.823 回答