如何在Windows Phone 8.1上执行POST操作

时间:2014-04-09 02:40:22

标签: windows-phone-8 asp.net-web-api windows-phone-8.1

我很难在POST内成功实施Windows Phone 8.1操作。

执行

PostMessage方法时不会捕获任何异常。 但是,POST中的MessagesController方法永远不会被调用。

如何为POST执行Windows Phone 8.1

代码如下:

internal async Task PostMessage(string text)
{
    Globals.MemberId = 1;
    int memberId = 2;

    // server to POST to
    string url = @"http://localhost:17634/api/messages";

    try
    {
        // 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
            var message = new Message() { FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
            var json = string.Format("{0}{1}", "action=", JsonConvert.SerializeObject(message));

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

            // Write the bytes to the stream
            await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
        }
    }
    catch(Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}


public class MessagesController : ApiController
{
    public HttpResponseMessage Post(Message message)
    {
        throw new NotImplementedException();
    }
}

public class Message
{
    public int MessageId { get; set; }
    public int FromId { get; set; }
    public int ToId { get; set; }
    public DateTime Timestamp { get; set; }
    public string Content { get; set; }
}

3 个答案:

答案 0 :(得分:1)

以下link解决了我的问题。 更新的客户端如下:

        using (var client = new System.Net.Http.HttpClient())
        {
            // New code:
            client.BaseAddress = new Uri(Globals.URL_PREFIX);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var message = new Message() { MessageId = 0, FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
            var json_object = JsonConvert.SerializeObject(message);

            var response = await client.PostAsync("api/messages", new StringContent(json_object.ToString(), Encoding.UTF8, "application/json"));
            Debug.Assert(response.StatusCode == System.Net.HttpStatusCode.Accepted);
        }

答案 1 :(得分:1)

这对我来说很好。该函数接受payload类型T。服务器接受JSON对象并返回JSON响应。

public async static Task SendRequestPacket<T>(object payload)
        {
            Uri theUri = new Uri("the_uri");
            //Create an Http client and set the headers we want 
            HttpClient aClient = new HttpClient();
            aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            aClient.DefaultRequestHeaders.Host = theUri.Host;

            //Create a Json Serializer for our type 
            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(T));

            // use the serializer to write the object to a MemoryStream 
            MemoryStream ms = new MemoryStream();
            jsonSer.WriteObject(ms, payload);
            ms.Position = 0;

            //use a Stream reader to construct the StringContent (Json) 

            StreamReader sr = new StreamReader(ms);
            StringContent theContent = new StringContent(sr.ReadToEnd(), Encoding.UTF8, "application/json");

            //Post the data 
            HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);

            if (aResponse.IsSuccessStatusCode)
            {
                string content = await aResponse.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine(content);
            }
            else
            {
                // show the response status code 
            }
        }

答案 2 :(得分:0)

如果您不以任何方式被迫,请不要使用HttpWebRequest。 此示例使用HttpClient(),最好始终创建一次客户端,而不是每次发出请求。

所以在你的课堂上添加:

private static HttpClient _client;

public static Uri ServerBaseUri
{
    get { return new Uri("http://localhost:17634/api"); }
}

public ClassConstructor()
{
_client = new HttpClient();
}

internal async Task<ResponseType> PostMessage(string text)
{
    Globals.MemberId = 1;
    int memberId = 2;

    try
    {
        var js = "{  JSON_OBJECT }";

        var json = new StringContent(js);
        json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        var response = await Client.PostAsync(new Uri(ServerBaseUri, "/messages"), json);

        var reply = await response.Content.ReadAsStringAsync();
    } catch (Exception)
    {
        return null;
    }
}

更多关于HttpClient