2012-11-30 156 views
3

我想從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在標題內......但這是不允許的,並拋出異常)

+0

你能證明'WebClient'代碼哪些工作正常嗎? – nkchandra

+0

爲你插入.. – Flo

+0

你試過這個'wc.Headers [「some header」] =「header value」;' – nkchandra

回答

4

你在哪裏設置標題? 這裏是如何做到這一點:

request.Headers["mycustomheader"] = "abc"; 
+1

Jea我知道。 httpWebRequest代碼的問題在於沒有任何請求到達服務器 – Flo

+0

@Flo - 因此更新您的問題以反映您嘗試執行此操作? –

+0

我以爲我說得很清楚。我想用customheaders發送請求。我試着用WebClient發送一個請求。有用。但我找不到在這裏設置自定義標題的方法。我嘗試用HttpWebRequest發送請求,因爲我發現可以在那裏設置一個customheader。無法讓它工作。沒有到達我的服務器。當我能夠使它工作時,設置標題的命令確實不是問題。該怎麼辦? – Flo