我想從Windows Phone 8向WCF服務器發送HTTP PUT請求,並且爲了標識我必須發送自定義標頭。 (假設「mycustomheader」 =「ABC」)Windows Phone 8 Http請求與自定義標頭
我用WebClient
到目前爲止,但Webclient.Headers
似乎沒有一個Add
方法,所以它不可能在HttpRequestHeader
枚舉發送其他頭則的人。有沒有辦法用WebClient
來做到這一點?
只見它可以設置自定義頁眉與HttpWebRequest
類,但我不能得到它做任何事情。我的測試代碼(基本上將樣品從http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx複製):
public void dosth()
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://mycomputer/message");
wr.Method = "PUT";
wr.ContentType = "application/x-www-form-urlencoded";
wr.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), wr);
allDone.WaitOne();
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string postData = "{'Command': { 'RequestType' : 'Status', 'Test' : '1' }}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
allDone.Set();
}
,我可以使用Wireshark看到:沒有什麼是到達我的電腦(相同的URL,一切工作正常與WebClient
..除了自定義標題)。在調試中,我可以看到GetRequestStreamCallback
被解僱並正在運行。但它永遠不會到達GetResponseCallback
。我發現關於這個的大多數東西是指像GetResponse()
這樣的方法,這些方法似乎不可用
這裏要走什麼路?是否有可能讓HttpWebRequest
正常工作,或者是否有一些解決方法來獲取WebClient
中的自定義標題集,或者是否有更好的方法?
編輯:Web客戶端代碼:
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentLength] = data.Length.ToString();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(new Uri("http://mycomputer/message"), "PUT", data);
發送正確的數據在正確的URL。但是,設置自定義標題似乎是不可能的。 (甚至試過\ r \ n在標題內......但這是不允許的,並拋出異常)
你能證明'WebClient'代碼哪些工作正常嗎? – nkchandra
爲你插入.. – Flo
你試過這個'wc.Headers [「some header」] =「header value」;' – nkchandra