【发布时间】:2012-11-30 09:34:44
【问题描述】:
我想从 Windows Phone 8 向 WCF 服务器发送一个 HTTP PUT 请求,并且为了识别我必须发送一个自定义标头。 (假设“mycustomheader”=“abc”)
到目前为止,我一直在使用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 中设置自定义标头,或者还有其他更好的方法吗?
编辑:网络客户端代码:
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代码运行良好吗? -
你试过这个
wc.Headers["some header"] = "header value";
标签: c# http httpwebrequest webclient windows-phone-8