2014-04-09 40 views
1

我正在努力在Windows Phone 8.1內成功實施POST操作。如何在Windows Phone 8.1上執行POST操作

PostMessage方法執行時沒有發現任何異常。 但MessagesController中的POST方法永遠不會被調用。

如何爲Windows Phone 8.1執行POST

的代碼如下:

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; } 
} 

回答

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); 
     } 
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

+0

我沒有看到在您的示例中聲明對象「讀者」的位置。隨着該行註釋,我試圖執行代碼。但是,我仍然沒有觀察到Post方法在我的控制器中執行。 –

+0

響應對象反映了以下狀態:StatusCode:500,ReasonPhrase:'內部服務器錯誤',版本:1.1, –

+0

我已將其更改爲'ReadAsStringAsync',以便您可以看到響應。請再次檢查答案。 –

1

這對我來說很好。該功能接受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 
      } 
     } 
相關問題