[WebService]httppost using WebService

  • 4232
  • 0
  • C#
  • 2016-06-30

摘要:[WebService]httppost using WebService

最近因為專案需要,所以做了一個小AP

讓這個小AP可以對Web Service做http post測試,

把以前的Code 挖出來 突然發現不能跑了!!!


private void button1_Click(object sender, EventArgs e)
{
     string postData = postStr.Text;
     byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

     try
     {	
     	System.Net.WebRequest request = System.Net.HttpWebRequest.Create(this.URL.Text.Trim());
     	request.Method = "POST";
     	request.ContentLength = data.Length;
     	request.ContentType = "application/x-www-form-urlencoded";

     	System.IO.Stream str = request.GetRequestStream();
     	str.Write(data, 0, data.Length);
     	str.Flush();
    
        System.Net.WebResponse response = request.GetResponse();
        System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
        string result = reader.ReadToEnd();
        richTextBox1.Text = result; 
     }
     catch (Exception ex)
     {
        ResponseData.Text = ex.StackTrace + ex.Message;
     }
}

之後才發現原來我以前Call的URL是aspx

查一查資料才發現 改成Web Service之後

在第二行 postStr.Test 要加上 你Call Method 的參數

另外URL也不是向以前一樣是xxx.aspx 要改為 WebService.asmx\Testing (要指定要測試的Method名稱)

我的範例是 postData

 

所以程式碼會改成 也只改了第3行


private void button1_Click(object sender, EventArgs e)
{
	string postData = "postData=" + richTextBox2.Text;
	byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
	try
	{
            System.Net.WebRequest request = System.Net.HttpWebRequest.Create(
            this.URL.Text.Trim());
            request.Method = "POST";
            request.ContentLength = data.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            System.IO.Stream str = request.GetRequestStream();
            str.Write(data, 0, data.Length);
            str.Flush();
            
                System.Net.WebResponse response = request.GetResponse();
                System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                string result = reader.ReadToEnd();
                richTextBox1.Text = result; 
            }
            catch (Exception ex)
            {
                richTextBox1.Text = ex.StackTrace + ex.Message;
            }
        }
}

結果發現還是不能跑原來是WebService 中的config需要再設定, 詳細可以上MSDN webService protocols查看喲


<?xml version="1.0"?>
<configuration>
  <appSettings/>
  <connectionStrings/>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpSoap"/>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
        <add name="Documentation"/>
      </protocols>
    </webServices>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

-----------------------------------------

有時在會走之前你就得跑

你不解決問題 就等問題解決你