2015-11-12 78 views
1

我試圖從PCL項目向遠程服務器發佈數據。下面是我的代碼:嘗試從PCL項目發佈數據時出現異常

public async Task<bool> SendToken(string deviceToken, string userId) 
     { 
      HttpWebRequest request; 
      string url = "http://192.168.1.171:91/api/updatePushDeviceToken"; 
      request = (HttpWebRequest)WebRequest.Create(url); 
      request.ContentType = "application/x-www-form-urlencoded"; 
      request.Accept = "application/json"; 
      request.Method = "POST"; 
      string postData = string.Format("userId={0};token={1}&deviceType={2}", userId, deviceToken, deviceType); 
      var data = Encoding.UTF8.GetBytes(postData); 

      try 
      { 
       request.BeginGetResponse(new AsyncCallback(FinishRequest), request);  
      } 
      catch (Exception e) 
      { 
       string m = e.Message; 
      } 

      return false; 
     } 

     private void FinishRequest(IAsyncResult result) 
     { 
      HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse; 

      Stream receiveStream = response.GetResponseStream(); 
      StreamReader readStream = new StreamReader(receiveStream); 

      var responseString = readStream.ReadToEnd(); 

     } 

運行上面的代碼雖然,以下異常被拋出:

System.Net.WebException: The remote server returned an error: (411) Length Required.

PCL不包含的ContentLength屬性,所以我增加的長度如下,但現在我得到的例外是:

try 
{ 
    request.Headers[HttpRequestHeader.ContentLength] = "0"; 
} 
catch (Exception e) 
{ 

} 

System.ArgumentException: This header must be modified with the appropiate property. at System.Net.WebHeaderCollection.CheckRestrictedHeader (System.String headerName)

+0

你做你的編碼數據,但實際上從未將其添加要求還是我錯過了什麼? – Adwaenyth

回答

0

您的請求缺少您的文章參數的ContentLength屬性。

  var parameters = Encoding.ASCII.GetBytes(qstring); 
      var request = (HttpWebRequest)HttpWebRequest.Create(url); 
      request.AllowAutoRedirect = false; 
      request.ContentType="application/x-www-form-urlencoded"; 
      request.Method = "POST"; 
      request.ContentLength = parameters.Length; 

      //Send it 
      var reqStream = request.GetRequestStream(); 
      reqStream.Write(parameters, 0, parameters.Length); 
      reqStream.Close(); 

     //read it 
      var response = (HttpWebResponse)request.GetResponse(); 
      var sr = new StreamReader(response.GetResponseStream()); 
      string responseHtml = sr.ReadToEnd().Trim(); 

而且請使用查詢字符串格式發佈數據,例如:「用戶id = {0} &令牌= {1} & ......」

+1

我正在開發.Net PCL項目,PCL中的WebRequest類沒有ContentLength屬性 – Subha

相關問題