0

may sound like a noob, but this problem is really not getting out of my mind.I am facing weird problem regarding Windows Phone 8.1 . I developed an application for Windows Phone 8 that communicates to the Gateway server and process the requested data. We used HttpClient to send/receive data to Gateway server.However, Due to some reasons, I upgraded Windows Phone 8 OS to Windows Phone 8.1 but now, It doesn't process the request whenever I communicate to the Gateway server.

However, It works fine on Windows 8.1 Emulator But doesn't work, when you deploy application on actual Windows Phone 8.1 device (Previously upgraded from Windows Phone 8.0 os).

Moreover
var response = await RequestUtility.SendHttpRequest(myUri, httpMethod, stream, "text/xml", null, null, 0); Response always contains 0 bytes whenever we run this application on Windows Phone 8.1.

Here is code snippet that communicate to the Server

public async Task<bool> ValidateUserRequest(User user)
        {
            var result = false;
            var myUri = new Uri(GatewayUrl);
            var content = RequestUtility.ValidateRequestBuilder(user);
            try
            {
                var httpMethod = new HttpMethod("POST");
                MemoryStream stream = new MemoryStream((new UTF8Encoding()).GetBytes(content.ToString(CultureInfo.InvariantCulture)));
                var response = await RequestUtility.SendHttpRequest(myUri, httpMethod, stream, "text/xml", null, null, 0);
                string ecodedString = Encoding.UTF8.GetString(response, 0, response.Length);
                var serializer = new XmlSerializer(typeof(ResponseType));
                ResponseType responseObject;
                using (var reader = new StringReader(ecodedString))
                {
                    responseObject = serializer.Deserialize(reader) as ResponseType;
                }
                if (responseObject != null) result = responseObject.Approved;
            }
            catch
            {
                result = false;
            }
            return result;
        }

Request Utility code Snippet

 public static async Task<byte[]> SendHttpRequest(Uri uri, HttpMethod method, Stream requestContent = null, string contentType = null, HttpClientHandler clientHandler = null, Dictionary<string, string> headers = null, int timeoutInSeconds = 0)
        {

            var req = clientHandler == null ? new HttpClient() : new HttpClient(clientHandler);
            var message = new HttpRequestMessage(method, uri);
            byte[] response;
            if (requestContent != null && (method == HttpMethod.Post || method == HttpMethod.Put || method == HttpMethod.Delete))
            {
                message.Content = new StreamContent(requestContent); //set the body for the request

                if (!string.IsNullOrEmpty(contentType))
                {
                    message.Content.Headers.Add("Content-Type", contentType); // if the request has a body set the MIME type

                }
            }

            // append additional headers to the request
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    if (message.Headers.Contains(header.Key))
                    {
                        message.Headers.Remove(header.Key);
                    }

                    message.Headers.Add(header.Key, header.Value);
                }
            }
            // Send the request and read the response as an array of bytes
            if (timeoutInSeconds > 0)
            {
                req.Timeout = new TimeSpan(0, 0, timeoutInSeconds);
            }
            using (var res = await req.SendAsync(message))
            {
                response = await res.Content.ReadAsByteArrayAsync();
            }
            return response;
        }

Any idea? Your ideas/suggestions would be appreciated.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • if it works in the emulator but not the device, I'd check to see what could possibly be different. Did the phone upgrade properly? Is it experiencing any other connectivity issues? Did you try making a new project and testing out a bare bones HttpRequest? – earthling Sep 08 '14 at 21:35
  • I have the same problem, my code works great on Windows 8.1 but not in Windows Phone 8.1 (empty response content)> Have you solve this issue ? – Geotinc Nov 14 '14 at 20:59

1 Answers1

0

I prefert to use httpwebrequest and httpwebresponse classes for to do a simple requests to server, use this:

    private async Task<string> DoRequest(string Type, string Device, string Version, string Os)
    {
        //Declarations of Variables
        string result = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContinueTimeout = 4000;

        request.Credentials = CredentialCache.DefaultNetworkCredentials;

        //Add headers to request
        request.Headers["Type"] = Type;
        request.Headers["Device"] = Device;
        request.Headers["Version"] = Version;
        request.Headers["Os"] = Os;
        request.Headers["Cache-Control"] = "no-cache";
        request.Headers["Pragma"] = "no-cache";

        using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                //To obtain response body
                using (Stream streamResponse = response.GetResponseStream())
                {
                    using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
                    {
                        result = streamRead.ReadToEnd();
                    }
                }
            }
        }

        return result;
    }

And for download a file, use this:

    private void DoSincroFit()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);

        //Add headers to request
        request.Headers["Type"] = "sincrofit";
        request.Headers["Device"] = "1";
        request.Headers["Version"] = "0.000";
        request.Headers["Os"] = "WindowsPhone";
        request.Headers["Cache-Control"] = "no-cache";
        request.Headers["Pragma"] = "no-cache";

        request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
    }

    public async void playResponseAsync(IAsyncResult asyncResult)
    {
        //Declaration of variables
        HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            string fileName = "sincrofit.rar";

            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
            {
                byte[] buffer = new byte[1024];

                var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new DataWriter(outputStream))
                        {
                            using (Stream input = webResponse.GetResponseStream())
                            {
                                var totalSize = 0;
                                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                {
                                    dataWriter.WriteBytes(buffer);
                                    totalSize += size;    //get the progress of download
                                }
                                await dataWriter.StoreAsync();
                                await outputStream.FlushAsync();
                                dataWriter.DetachStream();
                            }
                        }
                    }
                }

            }
        }
        catch
        {

        }

You can use this? Good luck!