我想从Windows Phone 8向WCF服务器发送HTTP PUT请求,并且为了身份识别,我必须发送自定义标头。(假设“mycustomheader”=“abc”)
到目前为止,我一直在使用WebClient,但是Webclient.Headers似乎没有Add方法,因此无法发送除HttpRequestHeader枚举中的标头之外的标头。是否有任何方法可以使用WebClient实现这一点?
我用Wireshark看到:我的电脑没有收到任何东西(使用
在这里应该怎么做?是否可能使
到目前为止,我一直在使用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看到:我的电脑没有收到任何东西(使用
WebClient
时,相同的URL和所有内容都正常工作..除了自定义标头)。在调试中,我可以看到GetRequestStreamCallback
被触发并运行。但它永远不会到达GetResponseCallback
。大多数相关信息都涉及像GetResponse()
这样的方法,似乎不可用于。在这里应该怎么做?是否可能使
HttpWebRequest
工作,或者是否有一些解决方案可以在WebClient
中设置自定义标头,甚至还有其他更好的方法吗?
编辑:webclient 代码:
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
代码吗? - nkchandrawc.Headers["some header"] = "header value";
- nkchandra