我試圖從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)
你做你的編碼數據,但實際上從未將其添加要求還是我錯過了什麼? – Adwaenyth