转载: http://www.01yun.com/dotnet_question/20121217/11019.html



在线等 HttpWebRequest post提交数据错误

我用HttpWebRequest post方式提交数据,如果参数中带有‘%’ 后台取数据就会报错,请问有没有什么方式可以将百分号传入进去的?

private bool Msg(string url, string contents, string method)

{

string postData = "method=" + method;

postData += ("&contents=" + contents);

byte[] data = Encoding.Default.GetBytes(postData); //web 请求

HttpWebRequest myrequest = (HttpWebRequest)WebRequest.Create(url);

myrequest.Method = "POST";

myrequest.ContentType = "application/x-www-form-urlencoded";

myrequest.ContentLength = data.Length;

Stream stream = myrequest.GetRequestStream();

//发送数据

stream.Write(data, 0, data.Length);

stream.Close();

//get response

HttpWebResponse response = (HttpWebResponse)myrequest.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

string content = reader.ReadToEnd();

reader.Close();

response.Close();

if (content.Trim() == "true")

return true;

else

return false;

}

标红处被编码了,请问如果不编码的话数据怎么发送呢? 请各位高手帮帮忙。


回答1:



1、应该不是%的问题吧,可能是你post的数据有问题

http://www.01yun.com/dotnet_question/20121217/11019.html

如:string postData = "method=" + method;应该是string postData = "&method=" + method;这样的吧??还有你post的数据只有这两项吗?

2、那个编码是为了把post的数据转换为字节数组,因为后面你写入到网络流的数据(stream.Write(data, 0, data.Length);)需要的是字节数组

回答2:



引用 1 楼 wm0508 的回复:1、应该不是%的问题吧,可能是你post的数据有问题

如:string postData = "method=" + method;应该是string postData = "&method=" + method;这样的吧??还有你post的数据只有这两项吗?

2、那个编码是为了把post的数据转换为字节数组,因为后面你写入到网络流的数据(stream.Wri……

+1

是你post的数据问题,有%不会有问题。。

回答3:



引用 1 楼 wm0508 的回复:1、应该不是%的问题吧,可能是你post的数据有问题

如:string postData = "method=" + method;应该是string postData = "&method=" + method;这样的吧??还有你post的数据只有这两项吗?

2、那个编码是为了把post的数据转换为字节数组,因为后面你写入到网络流的数据(stream.Write(data, 0, d……

只有这两个参数,当我传入的参数里面带有%号的就读取不到数据了

回答4:



http://www.01yun.com/dotnet_question/20121217/11019.html

用URLencoder

String sss = URLEncoder.encode( "%%", "utf-8" );

System.out.println( sss );

参考百度的%%处理

http://www.baidu.com/s?wd=%25%25