/// <summary>
/// 测试按钮中调用WebService接口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//string result = HttpPostWebService(textBox1.Text, textBox2.Text);
string result = HttpPostWebService("http://localhost:5000/StudentService.asmx", "<strInput>192.168.1.100</strInput>");
MessageBox.Show(result);
}
/// <summary>
/// 调用WebService接口
/// </summary>
/// <param name="url">请求接口地址</param>
/// <param name="strInput"></param>
/// <returns></returns>
public string HttpPostWebService(string url, string strInput)
{
string result = string.Empty;//返回值
//string param = string.Empty;//请求参数
byte[] bytes = null;
HttpWebRequest request = null;
Stream writer = null;
string responseString = string.Empty;//返回内容
// SOAP格式内容,参数为:xml
StringBuilder param = new StringBuilder();
param.Append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n");
param.Append("<soap:Body>\r\n");
param.Append("<Get xmlns=\"http://tempuri.org/\">\r\n");//请求方法名称
param.Append("<strInput>测试</strInput>");//请求参数
param.Append("</Get>\r\n</soap:Body>\r\n</soap:Envelope>");
try
{
//param = $"strInput={strInput}";//接收参数名称
bytes = Encoding.UTF8.GetBytes(param.ToString());
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.ContentLength = bytes.Length;
request.Timeout = 10000; // 设置请求超时时间为10秒
using (writer = request.GetRequestStream())
{
writer.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
`
标签:string,C#,bytes,request,param,result,HttpWebRequest,Net,Append
From: https://www.cnblogs.com/cplmlm/p/18241826