0

URL をパラメーターとして取り、そこから GET 応答を返す関数を作成しようとしていますが、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

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 に答える