通用Windows应用程序,使WebRequest方法= GET

时间:2015-06-25 10:54:30

标签: c# windows windows-10

有谁知道如何获得WebResponse?方法GetResponse()是obsolet,顺便说一下它是windows通用应用程序。

Uri uri = new Uri("myuri");
HttpClient httpclient = new HttpClient();
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(uri);
httpclient.DefaultRequestHeaders.Add("name", "value");
httpclient.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
webrequest.Method = "GET";
HttpWebResponse response = webrequest.GetResponseAsync();
StreamReader streamReader1 = new StreamReader(response.GetResponseStream());

解决:

用这个解决:private async void Start_Click(object sender,RoutedEventArgs e)         {

        response = new HttpResponseMessage();
        outputView.Text = "";

        httpClient.DefaultRequestHeaders.Add("name", "value");

        // The value of 'InputAddress' is set by the user and is therefore untrusted input. 
        // If we can't create a valid URI, 
        // We notify the user about the incorrect input.

        Uri resourceUri = new Uri("myuri")


        string responseBodyAsText;


        try
        {
            response = await httpClient.GetAsync(resourceUri);

            response.EnsureSuccessStatusCode();

            responseBodyAsText = await response.Content.ReadAsStringAsync();

        }
        catch (Exception ex)

        {
            // Need to convert int HResult to hex string
            statusText.Text = "Error = " + ex.HResult.ToString("X") +
                "  Message: " + ex.Message;
            responseBodyAsText = "";
        }





        // Format the HTTP response to display better
        responseBodyAsText = responseBodyAsText.Replace("<br>", Environment.NewLine);
        outputView.Text = responseBodyAsText;

1 个答案:

答案 0 :(得分:1)

您需要添加await关键字。

HttpWebResponse response = await webrequest.GetResponseAsync();