-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

you can try with this code

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 に答える