适用于Windows Phone 8的Http Post

9 c# http-post windows-phone

我是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开发人员有帮助.

更新 我现在正试图从服务器获得响应.我已经开始了一个新问题.请点击此链接(Http Post获取Windows Phone 8的响应错误)

Hun*_*len 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 这比ac #newbie更简单易懂.因为你正在使用`await`,如果我在该行之后调用一个函数,这是否正确,这是否意味着数据已成功发送?(如何从服务器获得响应?).. (4认同)

nem*_*ixx 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);            
}
Run Code Online (Sandbox Code Playgroud)