-1

我想使用 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;
                }
            }
4

2 回答 2

2
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";

using (var wc = new WebClient())
{
    byte[] result = wc.UploadValues(url,keyValues);
}
于 2012-08-21T10:09:22.603 回答
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();  
于 2012-08-21T09:55:58.697 回答