【发布时间】:2014-03-01 00:49:56
【问题描述】:
我的应用面向 Windows CE;它使用紧凑型框架
我复制了一些使用 WebClient 的其他工作代码,但它无法编译,说:“找不到类型或命名空间名称 'WebClient'(您是否缺少 using 指令或程序集参考?)“
我确实有一个“使用 System.Net;”
由于该错误,我还得到,“当前上下文中不存在名称'HttpRequestHeader'”
代码是:
private static void SendXMLFile(string xmlFilepath, string uri)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
// I don't know why the prepended equals sign is necessary, but it is
string allLines = "=" + sb.ToString();
var result = client.UploadString(uri, "POST", allLines);
}
}
如果 WebClient 可用于我的场景,我需要什么参考/使用?
如果 WebClient 对我的方案不可用,有什么资源/替代方法?
如果没有追索权/替代品,谁可以/将送我一瓶黑莓白兰地?
更新
我正在尝试根据我的情况调整答案,但马上遇到了问题:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = method;
问题是“方法”未被识别(得到红色波浪的情况和“当前上下文中不存在名称'方法'”
更新 2
我明白了——方法是传入的字符串;我需要的是:
request.Method = "POST";
更新 3
我还不确定这是否真的有效,但它确实可以编译,而且似乎很有意义,所以我会尝试一下:
private static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
【问题讨论】:
标签: visual-studio-2008 compact-framework windows-ce webclient system.net