2014-12-04 31 views
0

我是Windows Phone的新手。我有一個度假對象,我想在我的數據庫中更新。 我使用Spring的REST API,和我有一個方法:WindowsPhone的放置方法,以休息

@RequestMapping(value="/vacation", method = RequestMethod.PUT, consumes ="application/json") 
public void updateVacation(@RequestBody Vacation vacation){ 
    new VacationDao().update(vacation); 
} 

在我的Windows Phone應用程序,我有以下put方法:

public async void PushSubscription(Subscription subscription) 
    { 
     try 
     { 

      var httpWebRequest = (HttpWebRequest) WebRequest.Create(apiUrl); 
      httpWebRequest.ContentType = "text/plain; charset=utf-8"; 
      httpWebRequest.Method = "PUT"; 

      // Write the request Asynchronously 
      using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, 
       httpWebRequest.EndGetRequestStream, null)) 
      { 
       //create some json string 
       string json = JsonConvert.SerializeObject(subscription); 

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

       // Write the bytes to the stream 
       await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length); 
       MessageBox.Show("Ik geraak hier"); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

我沒有任何異常,我m確定我通過我的WP客戶端代碼,但我無法通過服務器上的代碼...

任何幫助嗎?

回答

0

它不解決將ContentType設置爲application/json而不是text/plain

您也可以嘗試使用HttpClient,它比我們每次創建WebRequest都更好地服務於我,您還可以編寫更少的代碼。

public async void PushSubscription(Subscription subscription) 
{ 
    try 
    { 
     string json = JsonConvert.SerializeObject(subscription); 

     using (HttpClient client = new HttpClient()) 
     { 
      await client.PutAsync(apiUrl, new StringContent(json, Encoding.UTF8, "application/json")); 
     } 

     MessageBox.Show("Ik geraak hier"); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
} 
+0

是的,這工作,非常感謝你! – Lumpi 2015-02-19 14:10:17