C# 利用http发送WebService请求和Rest 请求
本课题使用VS 2015完成
封装功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Xml;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace WMS.DEVICE
{
/// <summary>
/// send webservice message 发送webservice时 ,用post 发送
/// </summary>
class WebServiceClient
{
/// <summary>
/// 发送 post
/// </summary>
/// <param name="url"></param>
/// <param name="para"></param> 包含webservice的参数名称 和要请求的值
/// <param name="dataEncode"></param>
/// <returns></returns>
public string PostSend(string url, Dictionary<string,string> para, Encoding dataEncode)
{
//转换参数为string
string ret = string.Empty;
string param ="";
foreach(var item in para)
{
param += item.Key.ToString() + "=" + item.Value.ToString()+"&";
}
if(param.Length>0)
param=param.Remove(param.Length - 1);
try
{
byte[] byteArray = dataEncode.GetBytes(param); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.Timeout = 5000;
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
//读取报文内的值
XmlReader rd = XmlReader.Create(response.GetResponseStream());
rd.MoveToContent();
ret = rd.ReadInnerXml();
rd.Close();
rd.Dispose();
response.Close();
response.Dispose();
newStream.Close();
newStream.Dispose();
return ret;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
/// <summary>
/// 发送 rest 信息
/// </summary>
class PostMan
{
/// <summary>
/// POST
/// </summary>
/// <param name="postUrl"></param>
/// <param name="paramData"></param>
/// <param name="dataEncode"></param>
/// <returns></returns>
public string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string ret = string.Empty;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.Timeout = 5000;
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
ret = sr.ReadToEnd();
sr.Close();
sr.Dispose();
response.Close();
response.Dispose();
newStream.Close();
newStream.Dispose();
return ret;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// GET
/// </summary>
/// <param name="postUrl"></param>
/// <param name="paramData"></param>
/// <param name="dataEncode"></param>
/// <returns></returns>
public string GetWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string ret = string.Empty;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "GET";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.Timeout = 5000;
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
ret = sr.ReadToEnd();
sr.Close();
sr.Dispose();
response.Close();
response.Dispose();
newStream.Close();
newStream.Dispose();
return ret;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}`
调用
private void BtnClick(object para)
{
switch ((string)para)
{
case "Send":
if (PostInfo.Url=="")
{
MessageBox.Show("url不能为空");
return;
}
if(WebServiceEn)//web service模式
{
WebServiceClient ws = new WebServiceClient();
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in Labels)
{
dic.Add(item.Name, item.Value);
}
PostInfo.recvmsg = ws.PostSend(PostInfo.Url, dic,System.Text.Encoding.UTF8);
}else if(RestEn)//rest 模式
{
PostMan pm = new PostMan();
PostInfo.recvmsg = pm.PostWebRequest(PostInfo.Url, PostInfo.sendmsg, System.Text.Encoding.UTF8);
}
break;
}
}
页面效果
一个简单的WebService服务,将收到的parameters返回
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod(Description ="Request")]
//http://localhost:58932/WebService.asmx/Request
public string Request(string InterfaceId,int Factory,string User,string Password,string Parameters)
{
return Parameters;
}
}
输入webservice的地址
配置该Webservice参数
输入rest地址
输入参数
以上是利用Http来发送webservice和rest请求。
通常情况下我们需要传送结构体数据时,可以利用Newtonsoft来序列化和反序列结构体如下
webclient.getlot_request req = new getlot_request();
req.interfaceid = "123";
req.password = "123";
req.parameters = new request_para();
req.parameters.lineid = 20;
req.parameters.fromtime = "123";
webserviceclient ws = new webserviceclient();
dictionary<string, string> dic = new dictionary<string, string>();
dic.add("interfaceid", req.interfaceid.tostring());
dic.add("factory", req.interfaceid.tostring());
dic.add("user", req.interfaceid.tostring());
dic.add("password", req.interfaceid.tostring());
dic.add("parameters", jsonconvert.serializeobject(req.parameters));
postinfo.recvmsg = ws.postsend(postinfo.url, dic, system.text.encoding.utf8);
//jobject jo = jobject.parse(postinfo.recvmsg);
req.parameters = jsonconvert.deserializeobject<request_para>(postinfo.recvmsg);
return;