【C#】 通过http webRequest方式调用webservice
上一篇文章写了关于webservice的调用部署等内容,在上一篇文章中,我们通过微软给的方式--添加【WebReference服务引用】来进行调用如下图
那今天,我们说的是通过webrequest的方式进行接口调用,,废话少说了,,直接上代码截图(学习大神的说话方式--哈哈哈~~~)
具体步骤如下:
将参数写入Stream对象字节流
第一种返回ReadInnerXml ,,及xml中的值
第二种方式返回xml
第一种方式返回
第二种返回方式
今天的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Web;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
////调用方法一:引用webservice
//WebReference.WebServiceDemo webservice = new WebReference.WebServiceDemo();
//string a = textBox1.Text;
//string b = textBox2.Text;
//label1.Text = webservice.Add(a, b).ToString();
#region 通过http request调用
string url = "http://localhost:51270/WebServiceDemo.asmx";
string method = "Add";
string num1 = this.textBox1.Text;
string num2 = this.textBox2.Text;
string result = string.Empty;
string param = string.Empty;
byte[] bytes = null;
Stream writer = null;
HttpWebRequest request = null;
HttpWebResponse response = null;
param = ("a") + "=" + (num1) + "&" + ("b") + "=" + (num2);
bytes = Encoding.UTF8.GetBytes(param);
request = (HttpWebRequest)WebRequest.Create(url + "/" + method);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
try
{
writer = request.GetRequestStream(); //获取用于写入请求数据的Stream对象
}
catch (Exception ex)
{
// return "";
}
writer.Write(bytes, 0, bytes.Length); //把参数数据写入请求数据流
writer.Close();
try
{
response = (HttpWebResponse)request.GetResponse(); //获得响应
}
catch (WebException ex)
{
// return "";
}
#region 这种方式读取到的是一个返回的结果字符串
//Stream stream = response.GetResponseStream(); //获取响应流
//XmlTextReader Reader = new XmlTextReader(stream);
//Reader.MoveToContent();
//result = Reader.ReadInnerXml();
#endregion
#region 这种方式读取到的是一个Xml格式的字符串
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
#endregion
response.Dispose();
response.Close();
reader.Close();
reader.Dispose();
//Reader.Dispose();
//Reader.Close();
//stream.Dispose();
//stream.Close();
this.label1.Text = result;
#endregion
}
}
}