Http Post for Windows Phone 8

前端 未结 2 1043
[愿得一人]
[愿得一人] 2020-11-28 13:38

I am new to C# so I was wondering if someone can help me out on this. I am trying to send HttpPost from Windows Phone 8 to the server. I found two examples that I would li

相关标签:
2条回答
  • 2020-11-28 14:32

    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);            
    }
    
    0 讨论(0)
  • 2020-11-28 14:36

    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);
    }
    
    0 讨论(0)
提交回复
热议问题