Http Post for Windows Phone 8

人盡茶涼 提交于 2019-11-26 22:54:27

I am also currently working on a Windows Phone 8 project and here is how I am posting to a server. Windows Phone 8 sort of has limited access to the full .NET capabilities and most guide I read say you need to be using the async versions of all the functions.

// server to POST to
string url = "myserver.com/path/to/my/post";

// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";

// Write the request Asynchronously 
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,          
                                                         httpWebRequest.EndGetRequestStream, null))
{
   //create some json string
   string json = "{ \"my\" : \"json\" }";

   // convert json to byte array
   byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);

   // Write the bytes to the stream
   await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}

I propose a more generic asynchronous approach supporting success and error callbacks here:

//Our generic success callback accepts a stream - to read whatever got sent back from server
public delegate void RESTSuccessCallback(Stream stream);
//the generic fail callback accepts a string - possible dynamic /hardcoded error/exception message from client side
public delegate void RESTErrorCallback(String reason);

public void post(Uri uri,  Dictionary<String, String> post_params, Dictionary<String, String> extra_headers, RESTSuccessCallback success_callback, RESTErrorCallback error_callback)
{
    HttpWebRequest request = WebRequest.CreateHttp(uri);
    //we could move the content-type into a function argument too.
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "POST";

    //this might be helpful for APIs that require setting custom headers...
    if (extra_headers != null)
        foreach (String header in extra_headers.Keys)
            try
            {
                request.Headers[header] = extra_headers[header];
            }
            catch (Exception) { }


    //we first obtain an input stream to which to write the body of the HTTP POST
    request.BeginGetRequestStream((IAsyncResult result) =>
    {
        HttpWebRequest preq = result.AsyncState as HttpWebRequest;
        if (preq != null)
        {
            Stream postStream = preq.EndGetRequestStream(result);

            //allow for dynamic spec of post body
            StringBuilder postParamBuilder = new StringBuilder();
            if (post_params != null)
                foreach (String key in post_params.Keys)
                    postParamBuilder.Append(String.Format("{0}={1}&", key, post_params[key]));

            Byte[] byteArray = Encoding.UTF8.GetBytes(postParamBuilder.ToString());

            //guess one could just accept a byte[] [via function argument] for arbitrary data types - images, audio,...
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();


            //we can then finalize the request...
            preq.BeginGetResponse((IAsyncResult final_result) =>
            {
                HttpWebRequest req = final_result.AsyncState as HttpWebRequest;
                if (req != null)
                {
                    try
                    {
                        //we call the success callback as long as we get a response stream
                        WebResponse response = req.EndGetResponse(final_result);
                        success_callback(response.GetResponseStream());
                    }
                    catch (WebException e)
                    {
                        //otherwise call the error/failure callback
                        error_callback(e.Message);
                        return;
                    }
                }
            }, preq);
        }
    }, request);            
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!