universal windows app ,制作 WebRequest Method = GET

universal windows app , making a WebRequest Method = GET

有谁知道如何获取 WebResponse 吗?? GetResponse() 方法已过时,顺便说一句,它是 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;

您需要包含 await 关键字。

HttpWebResponse response = await webrequest.GetResponseAsync();