我想使用POST和webrequest在服务器上发布请求? 发布时我还需要传递参数吗? 如何在发布时传递参数?
我该怎么办?
示例代码......
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
答案 0 :(得分:2)
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
答案 1 :(得分:0)
您可以尝试使用此代码
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();