9

私はC#を初めて使用するので、誰かがこれを手伝ってくれるかどうか疑問に思っていました。WindowsPhone8からサーバーにHttpPostを送信しようとしています。組み合わせたい2つの例を見つけました。

1つ目は、Http Post( http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx )を送信する例です。これの問題は、WindowsPhone8ではサポートされていないことです。

2番目の例は、BeginGetResponse(http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.net.httpwebrequest (v=vs.105).aspx )を使用しています。これは、WindowsPhone8をサポートします。

2番目の例を最初の例のようにBeginGetRequestStream()に変換する必要があります。私はこれを自分で理解しようとしますが、誰かがこれを行う方法をすでに知っている場合は、オンラインで投稿しています。これは他のWP8開発者にも役立つと確信しています。

更新 サーバーから応答を取得しようとしています。新しい質問を始めました。このリンクをたどってください(Http Post Get Response Error for Windows Phone 8

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 に答える