简体   繁体   中英

WP8 HttpWebRequest Post Not Working

I have a Windows Phone Application and II am trying to post data in JSON format to a WCF application. Although the connection is made, the server returns with a custom message with

This is the C# code:

ReportSightingRequest.Instance.Source = Source.IPhone;
var jsonData = JsonConvert.SerializeObject(ReportSightingRequest.Instance);
var uri = new Uri("urlGoesHere", UriKind.Absolute);

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = jsonData.Length;

string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
    using (var responseStream = response.GetResponseStream())
    {
        using (var sr = new StreamReader(responseStream))
        {
            received = await sr.ReadToEndAsync();
        }
    }
}

This is the WCF Interface:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[Description("Description.")]
Response.Response ReportSighting(ReportSightingRequest sighting);

This is the implementation:

public Response ReportSighting(ReportSightingRequest sightingRequest)
{
    var response = new Response();
    if (sightingRequest == null || sightingRequest.TypeId == null)
    {
       response.Status = ResponseStatus.InvalidArguments;
       response.Message = "Request is null or no type has been supplied.";
       return response;
    }
...
}

When I call the ReportSighting method form the phone, I get a "Request is null or no type has been supplied" message. The strange thing is that I AM sending a TypeId and the sightingRequest object on the WP8 side is definitely not null when i'm sending it. When I put a breakpoint on the jsonData, it has everything in it. The ReportSightingRequest object too is exactly the same as the ReportSightingRequest in the WCF application.

It almost feels like that the object isn't being serialized. That's the only thing I can think of.

Does anyone have any ideas/suggestions?

Update

I've noticed that i'm actually not sending over the object. Shawn Kendrot's Answer seems to make sense but when I integrate his code, it returns with a Not Found error.

Update The following code works in a Console App:

        var jsonData = "a hard coded JSON string here";
        var uri = new Uri("a url goes here", UriKind.Absolute);
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json; charset=utf-8";
        webRequest.ContentLength = jsonData.Length;

        webRequest.BeginGetRequestStream(ar =>
        {
            try
            {
                using (var os = webRequest.EndGetRequestStream(ar))
                {
                    var postData = Encoding.UTF8.GetBytes(jsonData);
                    os.Write(postData, 0, postData.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            webRequest.BeginGetResponse(
                ar2 =>
                {
                    try
                    {
                        using (var response = webRequest.EndGetResponse(ar2))
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            var received = reader.ReadToEnd();
                            //Console.WriteLine(received);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }, null);
        }, null);

Update I have changed my code in WP8 to match that of Shawn Kendrot's solution. The problem which I am facing here is that I get a Not Found error message:

webRequest.BeginGetRequestStream(ar =>
            {
                try
                {
                    using (var os = webRequest.EndGetRequestStream(ar))
                    {
                        var postData = Encoding.UTF8.GetBytes(jsonData);
                        os.Write(postData, 0, postData.Length);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unsuccessful");
                }

                webRequest.BeginGetResponse(
                    ar2 =>
                    {
                        try
                        {
                            using (var response = webRequest.EndGetResponse(ar2))
                            using (var reader = new StreamReader(response.GetResponseStream()))
                            {
                                var received = reader.ReadToEnd();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unsuccessful");
                        }
                    }, null);
            }, null);

I get a:

{System.UnauthorizedAccessException: Invalid cross-thread access. at MS.Internal.XcpImports.CheckThread() at MS.Internal.XcpImports.MessageBox_ShowCore(String messageBoxText, String caption, UInt32 type) at System.Windows.MessageBox.ShowCore(String messageBoxText, String caption, MessageBoxButton button) at System.Windows.MessageBox.Show(String messageBoxText) at Notify.Logic.WebServices.<>c_ DisplayClass2.b _1(IAsyncResult ar2) at System.Net.Browser.ClientHttpWebRequest.<>c_ DisplayClass1d.b _1b(Object state2)}

When I try to do `MessageBox.Show(ex.Message);

Update

I have fixed the issue with the MessageBox.Show error message.

The webRequest.Headers object has the following:

{Content-Type: application/json; charset=utf-8;}

Your sightingRequest is null because you are not sending any data. To send data using a WebRequest, you need to use the BeginGetRequestStream method. This method allows you to package the data.

var webRequest= (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = jsonData.Length;
webRequest.BeginGetRequestStream(ar =>
{
    try
    {
        using (Stream os = webRequest.EndGetRequestStream(ar))
        {
            var postData = Encoding.UTF8.GetBytes(jsonData);
            os.Write(postData, 0, postData.Length);
        }
    }
    catch (Exception ex)
    {
        // Do something, exit out, etc.
    }

    webRequest.BeginGetResponse(
        ar2 =>
        {
            try
            {
                using (var response = webRequest.EndGetResponse(ar2))
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string received = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                // Do something, exit out, etc.
            }
        }, null);
}, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM