我正在开展一个项目,我必须通过HTTP POST中的HTTP POST将产品信息发送到Web服务器。事实证明,某些产品名称的名称可能有%符号,例如“.05%Topical Cream”。每当我尝试发送产品名称中包含%符号的XML数据时,我都会收到错误,因为在编码XML字符串数据时,百分号会导致数据格式错误。
如何安全地在产品名称中使用%符号编码和发送XML字符串数据?
XML数据:
<node>
<product>
<BrandName>amlodipine besylate (bulk) 100 % Powder</BrandName>
</product>
</node>
网络请求代码:
public string MakeWebServerRequest(string url, string data)
{
var parms = System.Web.HttpUtility.UrlEncode(data);
byte[] bytes = Encoding.UTF8.GetBytes("xml=" + parms);
string webResponse = String.Empty;
try
{
System.Web.HttpUtility.UrlEncode(data);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bytes.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.WriteTimeout = 3000;
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
webResponse = rdr.ReadToEnd();
rdr.Close();
}
response.Close();
}
}
我应该以不同方式创建Web请求吗?在维护产品名称的同时,我该如何解决?
已更正 - 现在正在使用。感谢
由于
答案 0 :(得分:1)
你需要正确地构建请求。 application/x-www-form-urlencoded
表示每个参数都是Url编码的。在您的情况下,xml
参数必须具有正确编码的值,而不是盲目连接。下面的示例应该让你盯着...希望你能够避免字符串连接来构造XML(以及用原始代码中的queotes构造字符串常量的疯狂方法):
var parameterValue = System.Web.HttpUtility.UrlEncode("<xml>" + data);
byte[] bytes = Encoding.UTF8.GetBytes("xml=" + parameterValue);
还有很多样本如何正确构建此类请求。即C# web request with POST encoding question