user2036340 user2036340 - 3 months ago 75
HTTP Question

Http Web Request Errors in UWP Application

I am using the Microsoft Translator API in .NET UWP application and I'm following the steps for obtaining an access token from the link:

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

I copied the code into my project, but I'm getting errors on the HttpWebRequest GetRequestStream() and GetResponse() methods saying it does not contain a definition for those. I believe the issue is that I'm using a UWP application since I tried it out in a console application and it worked.

Does anyone know how I can get this code to work in my UWP application? 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;
}
}

Answer

I copied the code into my project, but I'm getting errors on the HttpWebRequest GetRequestStream() and GetResponse() methods saying it does not contain a definition for those. I believe the issue is that I'm using a UWP application since I tried it out in a console application and it worked.

Yes,UWP is targeting .Net Core while console application is targeting normal .Net Framework.

Instead of GetRequestStream and GetResponse you can use the async version like below:

//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;
    }
}