9

我是 C# 的新手,所以我想知道是否有人可以帮助我解决这个问题。我正在尝试将 HttpPost 从 Windows Phone 8 发送到服务器。我找到了两个我想合并的例子。

第一个是发送 Http Post 的示例(http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx)。这个问题是 Windows Phone 8 不支持它。

第二个示例是使用 BeginGetResponse ( http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.net.httpwebrequest(v=vs.105).aspx )。这支持windows phone 8。

我需要像第一个示例一样将第二个示例转换为 BeginGetRequestStream()。我会尝试自己解决这个问题,但如果有人已经知道如何做到这一点,我会在网上发布。我相信这将对其他 WP8 开发人员有所帮助。

更新 我现在正试图从服务器获得响应。我开始了一个新问题。请点击此链接(Windows Phone 8 的 Http Post Get Response Error

4

2 回答 2

14

我目前也在做一个 Windows Phone 8 项目,这就是我发布到服务器的方式。Windows Phone 8 对完整 .NET 功能的访问权限有限,而且我阅读的大多数指南都说您需要使用所有功能的异步版本。

// 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);
}
于 2013-02-05T01:58:18.617 回答
6

我在这里提出了一种更通用的异步方法来支持成功和错误回调:

//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);            
}
于 2013-08-05T12:11:26.387 回答