UWP应用程序Http Web请求错误

本文关键字:请求 错误 Web Http 应用程序 UWP | 更新日期: 2023-09-27 18:03:40

我正在使用。net UWP应用程序中的Microsoft Translator API,并且我正在遵循从链接获取访问令牌的步骤:

https://msdn.microsoft.com/en-us/library/hh454950.aspx?f=255& MSPPError = -2147217396

我将代码复制到我的项目中,但我在HttpWebRequest GetRequestStream()和GetResponse()方法上得到错误,说它不包含那些定义。我认为问题是我使用的是UWP应用程序,因为我在控制台应用程序中尝试了它,并且它工作了。

有人知道我如何能得到这个代码在我的UWP应用程序工作吗?TIA。

private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
    {
        //Prepare OAuth request 
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(DatamarketAccessUri);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
        //webRequest.ContentLength = bytes.Length;
        using (Stream outputStream = webRequest.GetRequestStream())
        {
            outputStream.Write(bytes, 0, bytes.Length);
        }
        using (WebResponse webResponse = webRequest.GetResponse())
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            return token;
        }
    }  


当我遵循选中的答案时,我对上述代码所得到的错误进行了修复。然而,还有一个错误我试图修复-我遵循下面评论中的响应,当错误消失时,代码在

行退出。
 WebResponse response = await translationWebRequest.GetResponseAsync();

相关代码如下:

 //Exits on the WebResponse line
 private static async System.Threading.Tasks.Task<string> DetectMethod(string authToken, AdmAccessToken token, string txtToTranslate)
    {
        string headerValue = "Bearer " + token.access_token;
        string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + WebUtility.UrlEncode(txtToTranslate) + "&from=en&to=es";
        WebRequest translationWebRequest = WebRequest.Create(uri);
        translationWebRequest.Headers["Authorization"] = headerValue;
        WebResponse response = await translationWebRequest.GetResponseAsync(); //where it's exiting
        System.IO.Stream stream = response.GetResponseStream();
        System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
        System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
        xTranslation.LoadXml(translatedStream.ReadToEnd());
        translatedText = xTranslation.InnerText;
        return null;
    }
 //Where DetectMethod is called from
 public static async System.Threading.Tasks.Task<string> Translate(string TextToTranslate)
    {
        AdmAccessToken admToken;
        string headerValue;
        AdmAuthentication admAuth = new AdmAuthentication("<>", "<>");//codes removed
        try
        {
            admToken = admAuth.GetAccessToken();
            // Create a header with the access_token property of the returned token
            headerValue = "Bearer " + admToken.access_token;
            await DetectMethod(headerValue, admToken, TextToTranslate); //calls previous method
        }
        catch (WebException e)
        {
            ProcessWebException(e);
        }
        return translatedText;
    }

调用Translate()方法的方法在其签名中也有await用于调用该方法和async。同样,通过这些更改,不再有错误,但是程序在WebResponse行退出。

UWP应用程序Http Web请求错误

我将代码复制到我的项目中,但我在HttpWebRequest GetRequestStream()和GetResponse()方法上得到错误,说它不包含那些定义。我认为问题是我使用的是UWP应用程序,因为我在控制台应用程序中尝试了它,并且它工作了。

是的,UWP的目标是。net核心,而控制台应用程序的目标是正常的。net框架。

可以使用async版本代替GetRequestStreamGetResponse,如下所示:

//mark the method as async
private async System.Threading.Tasks.Task<AdmAccessToken> HttpPost(string DatamarketAccessUri, string requestDetails)
{
    ...
    //use 'GetRequestStreamAsync'
    using (Stream outputStream =await webRequest.GetRequestStreamAsync())
    {
        ...
    }
    //use 'GetResponseAsync' instead
    using (WebResponse webResponse = await webRequest.GetResponseAsync())
    {
        ...
        return token;
    }
}

Update:我使用翻译器API做了一个演示。代码如下:

MainPage.xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel VerticalAlignment="Center">
        <Button Name="myBtn" Click="myBtn_Click">Click Me</Button>
        <TextBlock Name="myTB"></TextBlock>
    </StackPanel>
</Grid>

MainPage.xaml.cs:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }
    private async void myBtn_Click(object sender, RoutedEventArgs e)
    {
        var translatedText = await Translate("Text for test");
        myTB.Text = translatedText;
    }
    //Exits on the WebResponse line
    private static async System.Threading.Tasks.Task<string> DetectMethod(string authToken, AdmAccessToken token, string txtToTranslate)
    {
        string headerValue = "Bearer " + token.access_token;
        string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + WebUtility.UrlEncode(txtToTranslate) + "&from=en&to=es";
        WebRequest translationWebRequest = WebRequest.Create(uri);
        translationWebRequest.Headers["Authorization"] = headerValue;
        WebResponse response = await translationWebRequest.GetResponseAsync(); //where it's exiting
        System.IO.Stream stream = response.GetResponseStream();
        System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
        System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
        xTranslation.LoadXml(translatedStream.ReadToEnd());
        //translatedText = xTranslation.InnerText;
        return xTranslation.InnerText;
    }
    //Where DetectMethod is called from
    public static async System.Threading.Tasks.Task<string> Translate(string TextToTranslate)
    {
        AdmAccessToken admToken;
        string headerValue;
        string translatedText=null;
        AdmAuthentication admAuth = new AdmAuthentication("<>", "<>");//codes removed
        try
        {
            admToken =await admAuth.GetAccessToken();
            // Create a header with the access_token property of the returned token
            headerValue = "Bearer " + admToken.access_token;
            translatedText= await DetectMethod(headerValue, admToken, TextToTranslate); //calls previous method
        }
        catch (WebException e)
        {
        }
        return translatedText;
    }
    public class AdmAccessToken
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string scope { get; set; }
    }
    public class AdmAuthentication
    {
        string clientID = "winffee_4960";
        string clientSecret = "N0aTQ4OUKKP5lpNIBs0h9wfFXGpHlel1BpIkmDd1cVE=";
        String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        String strRequestDetails;
        public AdmAuthentication(String str1, String str2)
        {
            strRequestDetails= string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", WebUtility.UrlEncode(clientID), WebUtility.UrlEncode(clientSecret));
        }
        public async Task<AdmAccessToken> GetAccessToken()
        {
            WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            //webRequest.ContentType = bytes.Length;
            using (Stream outputStream = await webRequest.GetRequestStreamAsync())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            WebResponse webResponse = await webRequest.GetResponseAsync();
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream 
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            string headerValue = "Bearer " + token.access_token;
            return token;
        }
    }
}