这篇文章介绍了C#中使用HttpPost调用WebService的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
WebService服务端代码
public class WebServiceDemo : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string Sum(string param1, string param2)
{
int num1 = Convert.ToInt32(param1);
int num2 = Convert.ToInt32(param2);
int sum = num1 + num2;
return sum.ToString();
}
}
客户端调用代码
class Program
{
static void Main(string[] args)
{
Program program = new Program();
string url = "http://localhost:12544/WebServiceDemo.asmx";
string method = "Sum";
string num1 = "1";
string num2 = "2";
string result = program.HttpPostWebService(url, method, num1, num2);
Console.WriteLine(result);
Console.ReadKey();
}
public string HttpPostWebService(string url,string method,string num1,string num2)
{
string result = string.Empty;
string param = string.Empty;
byte[] bytes = null;
Stream writer = null;
HttpWebRequest request = null;
HttpWebResponse response = null;
param = HttpUtility.UrlEncode("param1") + "=" + HttpUtility.UrlEncode(num1) + "&" + HttpUtility.UrlEncode("param2") + "=" + HttpUtility.UrlEncode(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();
return result;
}
}
如果遇到调用时报错,可以尝试在WebService的web.config配置文件中添加如下节点
<system.web>
<webServices>
<protocols>
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
到此这篇关于C#中使用HttpPost调用WebService的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:C#中使用HttpPost调用WebService的方法
基础教程推荐
猜你喜欢
- C# 调用WebService的方法 2023-03-09
- ZooKeeper的安装及部署教程 2023-01-22
- winform把Office转成PDF文件 2023-06-14
- C#控制台实现飞行棋小游戏 2023-04-22
- C#类和结构详解 2023-05-30
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- 一个读写csv文件的C#类 2022-11-06
- C# List实现行转列的通用方案 2022-11-02
- unity实现动态排行榜 2023-04-27
- C# windows语音识别与朗读实例 2023-04-27